We can pass a function as a parameter in Higher-Order 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.
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.
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:
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With