Given function foo :
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
We can do:
foo(\"a message\", { println
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) })
}
First-class functions are currently not supported in Kotlin. There's been debate about whether this would be a good feature to add. I personally think they should.
Kotlin 1.1
use ::
to reference method.
like
foo(::buz) // calling buz here
fun buz() {
println("i am called")
}
Jason Minard's answer is a good one. This could also be achieved using a lambda
.
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
val buz = { m: String ->
println("another message: $m")
}
Which can be called with foo("a message", buz)
.
You can also make this a bit more DRY by using a typealias
.
typealias qux = (m: String) -> Unit
fun foo(m: String, bar: qux) {
bar(m)
}
val buz: qux = { m ->
println("another message: $m")
}