Hi! Reading on smart cast in Kotlin and came up on...
# getting-started
h
Hi! Reading on smart cast in Kotlin and came up on following statement
When you're using a smart cast with a property of a class, the property has to be a val and it can't have a custom accessor. Otherwise, it would not be possible to verify that every access to the property would return the same value.
Makes sense but one thing that I don't understand is, what does the author mean
property has to be a val and it can't have a custom accessor
Doesn't val properties provide only getter methods?
a
it can’t be defined as
val someProperty get() = …
= custom accessor
h
why defining it as
val someProperty get() = ...
fails to verify that the val was changed?
q
Because the getter could return different things depending on what the ... Is
a
e.g.
val someProperty: String? get() = if (System.currentTimeMillis % 2 == 0) "hello" else null
- the nullness-or-not is unpredictable
h
Gotcha!