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 afterwards1val expensiveValue: String by lazy { // A side effect that shows when the computation actually happens2 println("Computing...") // The last expression becomes the property's value3 "Result"4}5 // Nothing has been computed yet: prints Before access6println("Before access")// First read: prints Computing..., then Result7println(expensiveValue)// Cached value: prints only Result8println(expensiveValue)Output
Before access Computing... Result Result
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