Kotlin: how to pass a function as parameter to another?

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)

Leave a Comment