Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

People also ask

Can I pass a function as a parameter in Kotlin?

We can pass a function as a parameter in Higher-Order function.

How do you pass a function as a parameter to another function?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

How do you pass parameters in Kotlin?

You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. In Kotlin, a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.

What is () -> unit in Kotlin?

Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.


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)

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) })
}

Just use "::" before method name

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

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

foo(::bar) Output : Hello World


Kotlin 1.1

use :: to reference method.

like

    foo(::buz) // calling buz here

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

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 })