Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are best practices for choosing between property initializer vs property getter in Kotlin?

Tags:

kotlin

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?

like image 545
Nikola Mihajlović Avatar asked Oct 23 '25 10:10

Nikola Mihajlović


1 Answers

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:

  • If the evaluation of Z changes over time, you probably want to evaluate it every time.
  • Even if 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.
  • Possibly the size of the result is large and you prefer not to retain it in memory while not being actively used. In that case prefer the custom getter.
like image 171
Marko Topolnik Avatar answered Oct 25 '25 22:10

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!