๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Function References

A callable reference is a value that points at a named function. Code can pass that value around and call the function through it.

A reference passed to a function

The test function receives a reference to isEven. It calls the reference on each number.

fun isEven(number: Int): Boolean {
    return number % 2 == 0
}

fun printResult(number: Int, test: (Int) -> Boolean) {
    println(test(number))
}

fun main() {
    printResult(6, ::isEven)
    printResult(7, ::isEven)
}

A reference in forEach

forEach needs a function that handles one element. The reference to printNumber does that job.

fun printNumber(number: Int) {
    println(number)
}

fun main() {
    val numbers = listOf(10, 20, 30)
    numbers.forEach(::printNumber)
}

A reference stored in a val

The val holds a reference to double. Calling the val runs the double function.

fun double(number: Int): Int {
    return number * 2
}

fun main() {
    val action = ::double
    println(action(21))
    println(action(3))
}

A property reference as a measure

String length is a property, and its reference works as a String to Int function. The showLength function receives that reference.

fun showLength(word: String, measure: (String) -> Int) {
    println(measure(word))
}

fun main() {
    showLength("kotlin", String::length)
    showLength("code", String::length)
}

Example

fun welcome(name: String) {
    println("Welcome, $name")
}

fun announce(action: (String) -> Unit, name: String) {
    action(name)
}

fun main() {
    announce(::welcome, "Ana")
    val greeter = ::welcome
    greeter("Ben")
    val names = listOf("Cid", "Dee")
    names.forEach(::welcome)
}

Key points

  • Two colons before a function name make a callable reference.
  • A callable reference fits where a function type is expected.
  • A reference stored in a val can be called just like the function itself.
  • A member reference points at a member of a class, such as a property.

In this example, announce receives a reference to welcome and calls it for Ana. The greeter val holds the same reference and calls it for Ben. forEach then calls the reference once for each name in the list.

Note

A callable reference names an existing function. It does not copy the function body.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does the expression ::double create?