still-dreaming-1
05/13/2020, 8:10 PMShawn
05/13/2020, 8:12 PMWill the get be called each time or is it gotten once and then reused?It will perform the logic in the getter each time it’s invoked. You can implement a sort of lazy or cached
val
in the getter, or you can have it execute a bunch of logic and return a potentially different value each time, though this is imo bad practice and I’d definitely flag it during code review lolShawn
05/13/2020, 8:14 PMval
s with open/custom getters are treated specially by the compiler if their return type is nullable, specifically you can’t directly smart cast what they returnstill-dreaming-1
05/13/2020, 8:18 PMCasey Brooks
05/13/2020, 8:31 PMvar
because you can’t set a value to it. Even though it computes a value every time, you can’t directly set that property to any specific value. As far as the compiler is concerned, a val
with get()
doesn’t even hold data, and it doesn’t even create a backing field for it. It’s basically just a function with different syntax. But like @Shawn said, doing this is probably better solved using something like a lazy { }
delegate, or moving it to an actual function for better clarityCasey Brooks
05/13/2020, 8:34 PMclass Foo {
// this property is a list that can be changed, but the list can also be reassigned
private var mutableBar: MutableList<String> = mutableListOf()
// this makes a read-only property that always returns the current state of mutableBar, not a cached copy of it
val readOnlyBar: List<String> get() = mutableBar
}
still-dreaming-1
05/13/2020, 8:36 PM