3 ms·
Simple answer here is just don't define custom getters, however I do agree that such functionality shouldn't even be allowed by the language for `val` propertie
by opmac 9y ago
Simple answer here is just don't define custom getters, however I do agree that such functionality shouldn't even be allowed by the language for `val` properties. Instead, if you want to define a custom getter, Kotlin should require that property to be a `var` (or `fun` since they're really functions).
- nostrademons 9y agoThat'd forbid a really common and innocuous use-case, where your custom val-getter is a simple function of other immutable data on the object. I use these all the time; they save on memory, allow lazy-init, and preclude the possibility of them getting out-of-sync with the source data if you later change their dependencies to mutable. (Although that introduces the issue described in the article; I would rather have code that is logically correct but surprising than code that is buggy.) A useful compromise might be for Kotlin to force 'var' if any of the fields used in the property body is itself a var, or is a function. It has this information already; it displays them in italics in the IDE, so no reason the compiler couldn't propagate that upwards.