by lazy
- Kotlin course
- Beginner
- Lesson 11/116
- 5 min
Learn lazy initialization with by lazy.
by lazy
With by lazy you compute a val's value on first access. This lets an expensive operation run only if it is really needed.
lazy is a delegate; the block runs the first time the variable is accessed and the result is stored, later accesses return the same result.
val bigData by lazy {
println("Computing")
1 + 2 + 3
}
fun main() {
println(bigData) // Computing, 6
println(bigData) // 6 (not recomputed)
}Practice Try by lazy
At the top level, declare val result by lazy { 2 * 3 }. Inside fun main(), print with println(result).
Sample solution
val result by lazy { 2 * 3 }
fun main() {
println(result)
}Expected output
6
by lazy vs lateinit
by lazy and lateinit both provide deferred initialization but in different ways. by lazy is for val only and the value is computed from a block; it runs automatically on first access.
lateinit is for var only and you assign the value manually; if it is not assigned before access, it throws. by lazy is thread-safe, lateinit is not.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 by lazy: fill in the missing part
val result ____ lazy { 1 + 2 }
val result by lazy { 1 + 2 }
Explanation: by lazy defines a lazy value.
2 When does by lazy compute?
- At compile time
- On every access
- On first access Correct answer
- Never
Explanation: by lazy computes only on first access and caches.
3 by lazy: match the terms
| Term | Meaning |
|---|---|
by lazy |
On first access |
lateinit |
Assigned later |
const val |
Compile-time |
val |
Assigned once |