In Kotlin, we have a choice between:
class|object X {
[override] val y = Z
}
and
class|object X {
[override] val y: Y
get() = Z
}
Which one should be chosen and when?
Decide based on when you want evaluation to happen. A property initializer results in memoization semantics: the initializing expression is evaluated only at instantiation time:
class X {
val y = Z // Z evaluated only at instantiation time
}
A property getter is evaluated every time you access the property:
class X {
val y get() = Z // evaluated on every access of y
}
There are several factors that may make you prefer one or the other:
Z changes over time, you probably want to evaluate it every time.Z always yields the same result, you may want to postpone the evaluation untill first access. In that case you may use a lazy property delegate.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With