Kotlin: how to pass a function as parameter to another?
Kotlin 1.1
use ::
to reference method.
like
foo(::buz) // calling buz here
fun buz() {
println("i am called")
}
Just use "::" before method name
fun foo(function: () -> (Unit)) {
function()
}
fun bar() {
println("Hello World")
}
foo(::bar)
Output : Hello World
About the member function as parameter:
- Kotlin class doesn't support static member function, so the member function can't be invoked like: Operator::add(5, 4)
- Therefore, the member function can't be used as same as the First-class function.
- A useful approach is to wrap the function with a lambda. It isn't elegant but at least it is working.
code:
class Operator {
fun add(a: Int, b: Int) = a + b
fun inc(a: Int) = a + 1
}
fun calc(a: Int, b: Int, opr: (Int, Int) -> Int) = opr(a, b)
fun calc(a: Int, opr: (Int) -> Int) = opr(a)
fun main(args: Array<String>) {
calc(1, 2, { a, b -> Operator().add(a, b) })
calc(1, { Operator().inc(it) })
}
Use ::
to signify a function reference, and then:
fun foo(msg: String, bar: (input: String) -> Unit) {
bar(msg)
}
// my function to pass into the other
fun buz(input: String) {
println("another message: $input")
}
// someone passing buz into foo
fun something() {
foo("hi", ::buz)
}
Since Kotlin 1.1 you can now use functions that are class members ("Bound Callable References"), by prefixing the function reference operator with the instance:
foo("hi", OtherClass()::buz)
foo("hi", thatOtherThing::buz)
foo("hi", this::buz)