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

Kotlin Property References

A property reference points at a property itself instead of reading its value at once. Code can read and write the property later through that reference.

The name and the first value

The ref value points at the counter property. Its name prints counter, and a get call reads the starting value.

var counter: Int = 0

fun main() {
    val ref = ::counter
    println(ref.name)
    println(ref.get())
}

Writing through the reference

The set call writes 9 through the reference. Both a get call and a direct read of counter then show 9.

var counter: Int = 0

fun main() {
    val ref = ::counter
    ref.set(9)
    println(ref.get())
    println(counter)
}

A bound property reference

This reference is bound to the items property of one crate. Reading through it gives the item count of that crate.

class Crate(val items: Int)

fun main() {
    val crate = Crate(12)
    val ref = crate::items
    println(ref.name)
    println(ref.get())
}

A reader built from a reference

The showValue function takes a reader with no arguments. The lambda handed to it reads the counter through the reference.

var counter: Int = 0

fun showValue(reader: () -> Int) {
    println(reader())
}

fun main() {
    val ref = ::counter
    ref.set(4)
    showValue { ref.get() }
}

Example

var counter: Int = 0

class Crate(val items: Int)

fun main() {
    val ref = ::counter
    println(ref.name)
    ref.set(15)
    println(ref.get())
    println(counter)
    val crate = Crate(3)
    val itemsRef = crate::items
    println(itemsRef.get())
}

Key points

  • Two colons before a top-level property name make a property reference.
  • The name property of the reference gives the property name.
  • The get call reads the current value through the reference.
  • The set call writes a new value through the reference.
  • A write through the reference changes the property itself.
  • A bound property reference is tied to one instance.

In this example, the reference first reports the property name counter. The set call writes 15, and both the reference and the property itself then read 15. A second reference bound to a crate reads its item count of 3.

Note

A reference to a var can read and write, because the property itself can change.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

After ref.set(9) runs on a reference to counter, what does ref.get() return?