Predict the output
What does this print?
class Report {
val total: Int by lazy {
println("computing")
42
}
}
fun main() {
val r = Report()
println("created")
println(r.total)
println(r.total)
}Hint 1 of 1
When does a lazy block run, and how often?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A created, computing, 42, 42
Correct. lazy runs once, on first access, then returns the cached value.
Why not the others?
- B computing, created, 42, 42. Nothing runs at construction.
- C created, computing, 42, computing, 42. The value is cached after the first read.
- D created, 42, 42. The lambda's println runs on first access.