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
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 can use your max
function as default
fun someDefault(f: (a: Int, b: Int) -> Int = max) {
f(1, 7)
// do something
}
or you can also define a method with lambda as parameter which is optional
fun someOptional(f: ((a: Int, b: Int) -> Int)? = null) {
f?.invoke(1, 7)
}
In both cases (default and optional) you can specify a lambda for the call or you can just omit it
fun call() {
someDefault()
someDefault { a, b -> a * b}
someOptional()
someOptional { a, b -> a * b}
}
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))
}
© 2022 - 2024 — McMap. All rights reserved.
max
function available in the JDK, accessible viaMath.max(a, b)
which does the same thing. – Nerlandmax
as a normal argument to any function call that takes a function of the form(Int, Int) -> Int
. – Nerland