How bad is it if `val` property doesn't always ret...
# codingconventions
k
How bad is it if
val
property doesn't always return the same value? Say it has a getter, and does some computation on other mutable parts of the class. Is it horrible? Amazingly bad?
p
I would make this a function to make it clear to consumers that it’s calculated
But that might be Java habits bleeding through
k
yeah, that definitely seems like the smarter choice!
interestingly, Kotlin wont smart cast such fields... so there's no opportunity for null to sneak past
k
It's not bad, considering there's plenty of existing usage of non-constant
val
properties even in the Kotlin API itself, such as
List.size
.
1
m
I agree that it is not bad as long as it only changes when some property of the object changes, like
List.size
. If it is something that is calculated randomly or has side effects, then being a
val
would be bad.
2
e
https://kotlinlang.org/docs/reference/coding-conventions.html#functions-vs-properties
Prefer a property over a function when the underlying algorithm:
• does not throw
• is cheap to calculate (or cached on the first run)
• returns the same result over invocations if the object state hasn't changed
so if it returns a different value without state changes, it's recommended not to use a
val
👍 2