Functional (fun) Interfaces

SAM Conversion

An interface with exactly one abstract function can be declared as fun interface. Then you can create an implementation with a lambda instead of an object - this is called SAM conversion (Single Abstract Method). Android's View.OnClickListener works the same way.

Example

fun interface PriceRule {
    fun apply(price: Double): Double
}

fun checkout(price: Double, rule: PriceRule) =
    println("Price ${price} -> ${rule.apply(price)}")

fun main() {
    val festiveSale = PriceRule { it * 0.8 }          // lambda becomes a PriceRule
    val flatOff = PriceRule { p -> if (p > 1000) p - 150 else p }
    checkout(2000.0, festiveSale)
    checkout(2000.0, flatOff)
    checkout(500.0, flatOff)
}

Output

Price 2000.0 -> 1600.0
Price 2000.0 -> 1850.0
Price 500.0 -> 500.0

Android Example

// Java interface View.OnClickListener has one method, so a lambda works:
binding.loginButton.setOnClickListener { view ->
    viewModel.login()
}