Kotlin val difference getter override vs assignment

The key difference here is that in val isEmpty get() = ... the body is evaluated each time the property is accessed, and in val isEmpty = ... the expression on the right hand side gets evaluated during the object construction, the result is stored in the backing field and this exact result is returned each time the property is used.

So, the first approach is suitable when you want the result to be calculated each time, while the second approach is good when you want the result to be calculated only once and stored.


In your second example size is immutable value and therefore both ways are valid.

However variant with overridden getter get() = size == 0 has no backing field and therefore size == 0 is evaluated every time you access isEmpty variable.

On the other hand, when using initializer = size == 0 the expression size == 0 is evaluated during construction (check exactly when and how here - An in-depth look at Kotlin’s initializers) and stored to the backing field, of which value is then returned when you access the variable.

Tags:

Getter

Kotlin