Property Delegates

In other words, let’s find out more about how to be lazy!

A Refresher on lazy

Back in the chapter on properties, we saw by lazy syntax:

class Foo(val rawLabel: String) {
  var count = 0
  val label: String by lazy { println("initializing via lazy!"); rawLabel.toUpperCase() }

  fun something() {
    count += 1
    println("$label: something() was called $count times")
  }
}

fun main() {
  val foo = Foo("foo")

  foo.something()
  foo.something()
  foo.something()

  println("the final count was ${foo.count}")
}

Here, label is computed lazily. If the code were:

val label = rawLabel.toUpperCase()

…then label would be populated immediately. Instead, by lazy will evaluate the supplied lambda expression when label is first accessed.

In this particular example, there is no practical difference, since rawLabel is a val property and will not change during the lifetime of label, and we are always accessing label. However, by lazy is useful if:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.