Function References
In this page:
Referencing a Top-Level Function
::functionName refers to an existing standalone function, letting it be passed directly wherever a matching function type is expected, without wrapping it in a lambda.
Example: Referencing a Top-Level Function
fun isEven(n: Int): Boolean = n % 2 == 0
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter(::isEven)
println(evens)
}
Login to try C/C++/Java/PHP code in the editor
Referencing a Member Function on an Instance
instance::method creates a bound reference to a member function tied to that specific object, usable directly as a function value.
Example: Referencing a Member Function on an Instance
class Greeter(val greeting: String) {
fun greet(name: String) = "$greeting, $name!"
}
fun main() {
val greeter = Greeter("Hi")
val greetFn: (String) -> String = greeter::greet
println(greetFn("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
Referencing a Member Function on a Class
ClassName::method creates an unbound reference, where the receiver instance must be supplied as the first argument when the reference is actually called.
Example: Referencing a Member Function on a Class
data class Person(val name: String) {
fun shout() = name.toUpperCase()
}
fun main() {
val shoutFn: (Person) -> String = Person::shout
println(shoutFn(Person("ana")))
}
Login to try C/C++/Java/PHP code in the editor
Constructor References
::ClassName creates a reference to a class's constructor, which can be used just like a function that builds new instances.
Example: Constructor References
data class Point(val x: Int, val y: Int)
fun main() {
val coordinates = listOf(1 to 2, 3 to 4)
val points = coordinates.map { (x, y) -> Point(x, y) }
println(points)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
::syntax and trying to pass a function's name alone, which Kotlin interprets as trying to call it rather than reference it. - Using a function reference where the referenced function's signature doesn't actually match what the receiving parameter expects.
- Not realizing member function references need either a bound receiver (
instance::method) or an unbound one (ClassName::method) depending on how they'll be called.
::functionNamecreates a reference to an existing top-level or member function, which can be passed wherever a matching function type is expected.ClassName::methodcreates an unbound reference, expecting the receiver as the first parameter when called.instance::methodcreates a bound reference tied to that specific instance.- Function references are useful for passing existing functions directly to higher-order functions instead of wrapping them in a lambda.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: