🎓 A1Learner
🔍
0 of 28 lessons completed

Kotlin References at Depth

A callable reference can point at a constructor, a function, or a property of a value. References at this depth build values and read members through a stored reference.

A constructor reference builds a value

The make value holds a reference to the Point constructor. Calling make with two numbers builds a Point from them.

data class Point(val x: Int, val y: Int)

fun main() {
    val make: (Int, Int) -> Point = ::Point
    val point = make(2, 3)
    println(point)
    println(point.x)
    println(point.y)
}

A function reference carries a name

The check value holds a reference to isEven. Its name property prints the function name, and calling it runs the function.

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

fun main() {
    val check = ::isEven
    println(check.name)
    println(check(4))
    println(check(7))
}

A bound reference to uppercase

The reference is bound to the word kotlin itself. Calling it needs no argument, because the word is already fixed inside the reference.

fun main() {
    val shout: () -> String = "kotlin"::uppercase
    println(shout())
}

A bound reference to length

The length property of the word hello is bound into a reference. Calling the reference reads the length of that one word.

fun main() {
    val size: () -> Int = "hello"::length
    println(size())
}

Example

data class Point(val x: Int, val y: Int)

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

fun main() {
    val make: (Int, Int) -> Point = ::Point
    val point = make(1, 4)
    println(point)
    val check = ::isEven
    println(check.name)
    println(check(point.y))
    val shout: () -> String = "kotlin"::uppercase
    println(shout())
    val size: () -> Int = "hello"::length
    println(size())
}

Key points

  • Two colons before a class name make a constructor reference.
  • A constructor reference fits a function type that matches the constructor parameters.
  • Calling the reference builds a new value of the class.
  • Two colons after a value make a bound reference to a member of that value.
  • A bound reference needs no extra argument when it runs.
  • The name property of a function reference gives the name of the function.

In this example, the constructor reference builds a point with x 1 and y 4. The function reference reports its name and tests the y value, which is even. The two bound references then read members of their fixed words.

Note

A reference is a value, so a program can store it and call it later.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Kotlin Playground

Exercise

What does the value ::Point hold?