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

Solution 1:

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)

Solution 2:

About the member function as parameter:

  1. Kotlin class doesn't support static member function, so the member function can't be invoked like: Operator::add(5, 4)
  2. Therefore, the member function can't be used as same as the First-class function.
  3. 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) })
}

Solution 3:

Just use "::" before method name

fun foo(function: () -> (Unit)) {
   function()
}

fun bar() {
    println("Hello World")
}

foo(::bar) Output : Hello World

Solution 4:

Kotlin 1.1

use :: to reference method.

like

    foo(::buz) // calling buz here

    fun buz() {
        println("i am called")
    }

Solution 5:

If you want to pass setter and getter methods.

private fun setData(setValue: (Int) -> Unit, getValue: () -> (Int)) {
    val oldValue = getValue()
    val newValue = oldValue * 2
    setValue(newValue)
}

Usage:

private var width: Int = 1

setData({ width = it }, { width })