Function References
suggest changeWe can reference a function without actually calling it by prefixing the function’s name with ::. This can then be passed to a function which accepts some other function as a parameter.
fun addTwo(x: Int) = x + 2
listOf(1, 2, 3, 4).map(::addTwo) // [3, 4, 5, 6]
Functions without a receiver are converted to (ParamTypeA, ParamTypeB, ...) -> ReturnType, where ParamTypeA, ParamTypeB, … are the types of the function parameters and ReturnType is the type of the function’s return value.
fun foo(p0: Foo0, p1: Foo1, p2: Foo2): Bar {
//...
}
println(::foo::class.java.genericInterfaces[0])
// kotlin.jvm.functions.Function3<Foo0, Foo1, Foo2, Bar>
// Human readable type: (Foo0, Foo1, Foo2) -> Bar
Functions with a receiver (whether an extension function or a member function) have a different syntax. Add the type name of the receiver before the double colon:
class Foo
fun Foo.foo(p0: Foo0, p1: Foo1, p2: Foo2): Bar {
//...
}
val ref = Foo::foo
println(ref::class.java.genericInterfaces[0])
// kotlin.jvm.functions.Function4<Foo, Foo0, Foo1, Foo2, Bar>
// Human readable type: (Foo, Foo0, Foo1, Foo2) -> Bar
// takes 4 parameters, with receiver as first and actual parameters following, in their order
// this function can't be called like an extension function, though
Foo().ref(Foo0(), Foo1(), Foo2()) // compile error
class Bar {
fun bar()
}
print(Bar::bar) // works on member functions, too.
However, when a function’s receiver is an object, the receiver is omitted from the parameter list, because there is only one instance of that type.
object Foo
fun Foo.foo(p0: Foo0, p1: Foo1, p2: Foo2): Bar {
//...
}
val ref = Foo::foo
println(ref::class.java.genericInterfaces[0])
// kotlin.jvm.functions.Function3<Foo0, Foo1, Foo2, Bar>
// Human readable type: (Foo0, Foo1, Foo2) -> Bar
// takes 3 parameters, receiver not needed
object Bar {
fun bar()
}
print(Bar::bar) // works on member functions, too.
Since Kotlin 1.1, a function reference can also be bound to a variable. That is called a bound function reference.
fun makeList(last: String?): List<String> {
val list = mutableListOf("a", "b", "c")
last?.let(list::add)
return list
}
Note this example is given only to show how bounded function reference works. It’s bad practice in all other senses.
There is a special case, though. An extension function declared as a member can’t be referenced.
class Foo
class Bar {
fun Foo.foo() {}
val ref = Foo::foo // compile error
}