How can I pass lambda expression as optional parameter in Kotlin language
val max = { a: Int, b: Int ->
if (a > b)
a
else
b
}
I have to pass above thing is like optional parameter
You use lambda expressions extensively in Android development and more generally in Kotlin programming.
Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.
A lambda expression is a shorter way of describing a function. It doesn't need a name or a return statement. You can store lambda expressions in a variable and execute them as regular functions. They can also be passed as parameters to other functions or be the return value.
The following defines a function that accepts a function, and specifies a default value for the passed function if none is supplied.
fun foobar(fn: (a: Int, b: Int) -> Int = { a: Int, b: Int -> if (a > b) a else b }) {
println(fn(42, 99))
}
You can pass your own functions:
val min = { a: Int, b: Int -> if (a <= b) a else b }
foobar(min)
val max = { a: Int, b: Int -> if (a > b) a else b }
foobar(max)
You can omit the function and use the default:
foobar()
Alternatively you could refer to the standard library maxOf
function as the default, rather than write your own:
fun foobar(fn: (a: Int, b: Int) -> Int = ::maxOf) {
println(fn(42, 99))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With