Lazy property in Kotlin

Level 4145 keystrokes

by lazy delays computing a value until it is first read, then caches it. That is why "Computing..." appears after "Before access" and only once, even though the property is read twice.

Kotlin code

// by lazy: the block runs on the first read, and its result is reused afterwards
1val expensiveValue: String by lazy {
// A side effect that shows when the computation actually happens
2 println("Computing...")
// The last expression becomes the property's value
3 "Result"
4}
5
// Nothing has been computed yet: prints Before access
6println("Before access")
// First read: prints Computing..., then Result
7println(expensiveValue)
// Cached value: prints only Result
8println(expensiveValue)

Output

Before access
Computing...
Result
Result
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • "× 6
  • (× 4
  • )× 4
  • .× 3
  • :× 1
  • {× 1
  • }× 1

More Kotlin examples at level 4

← Kotlin typing practice