https://kotlinlang.org logo
Title
k

Karlo Lozovina

02/18/2022, 5:33 PM
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

Paul Griffith

02/18/2022, 5:40 PM
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

Karlo Lozovina

02/18/2022, 5:52 PM
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

Klitos Kyriacou

02/18/2022, 6:31 PM
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

mkrussel

02/18/2022, 6:41 PM
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

ephemient

02/20/2022, 3:20 PM
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