androidengineers.Book a session

Reflection and Runtime Features

Callable References

article15 minHard

Callable references name existing behavior

Use ::function or Type::member when an existing declaration matches the needed function shape. Bound references capture an instance; unbound references take the receiver as an argument.

class Prefixer(private val prefix: String) {
    fun label(text: String): String = prefix + text
}

fun main() {
    val prefixer = Prefixer("Study: ")
    val bound: (String) -> String = prefixer::label
    val unbound: (Prefixer, String) -> String = Prefixer::label
    check(bound("Kotlin") == unbound(prefixer, "Kotlin"))
}

A bound reference retains its receiver, which matters when callbacks outlive screens or other short-lived owners. Overloaded functions may require an explicit function type to resolve the intended declaration.

Exercise

Replace a lambda forwarding directly to label with a bound reference, then compare a lambda that also normalizes input. Keep the lambda when adaptation makes the behavior clearer.

Check: callable-reference syntax does not guarantee no allocation or no captured state; the receiver and usage determine those properties.

Reference: Bound callable references

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Callable References | Kotlin Core Programming | Android Engineers