I am looking at docs and see this. Why wouldn't `i...
# announcements
a
I am looking at docs and see this. Why wouldn't
isEmpty
be a function? Also wouldn't the value stored in
isEmpty
never be referenced?
o
In this case property doesn’t have a backing field.
a
aight thanks
s
What's the recommended pattern here, btw? Myself, when I see that something is declared a
val
, and I know that the type that the
val
is referencing is deeply immutable (like a
Boolean
), I want to believe that what I receive from accessing the property is the same every time. Of course, with the case of custom getters like this, it's not necessarily the same every time, like if this is a property defined in a mutable list. Essentially, what I'm wondering if it's “OK” to write code like this, where the deeply immutable “contents” of a
val
can change from each invocation of the getter.
a
well, it is in official docs, so I would guess so
same with how you would define a lambda as
val
even though a lambda can change outputs
s
Sure, but a “pure lambda” wouldn't have that same problem, right?
a
we aren't assigning different getter logic, so it doesn't make sense to have it
var
(imo)
s
No, I'm thinking that in cases like this it might make “more sense” to have a function
isEmpty(): Boolean
instead, perhaps?
a
oh, I see
yeah, I'd agree too probably... most things could be computed in a field getter
even when it makes more sense to be in a func
s
Of course,
val
does not by any means suggest that the thing referenced is immutable, but that's another topic. One could, for instance, have a
val names: MutableList<String>
.