Hey guys, is it ok to use kotlin getter like that...
# android
r
Hey guys, is it ok to use kotlin getter like that (theoretical example):
Copy code
val isTooLate: Boolean
   get() = System.currentTimeMillis() > someTimestamp
I find it confusing that hovering over it in the IDE gives: public final val isTooLate: Boolean which gives an impression that this value is going to be always the same - but it's not.
v
By final the IDE means that you are not able to set it to a different value, i.e. you can't call
isTooLate = false
or
isTooLate = true
. Its definition is final, even thought its result may change.
👍 1
r
you are right it is about forbidding to override it!
but reading some answers on stackoverflow on a
val
bit of it: val is like Final variable and it's known as immutable in kotlin and can be initialized only single time. They point out that it is immutable but in reality it is just a read only *var*iable - so it seems that ppl wrongly expect it to be immutable Regarding the example I provided - in that situation, would you use
val
with
get {}
or would you use a function
fun isTooLate(): Boolean
?
and that raises another question: when to use argument-less function syntax?
r
That's more a style choice but would recommend following kotlin's own guidelines: https://kotlinlang.org/docs/coding-conventions.html#functions-vs-properties
👍 2
Clearly the third point (returns the same result over invocations if the object state hasn't changed) doesn't hold here so a fun makes more sense
3
In fact you actually have a hidden external dependency in System.currentTimeMillis()
May be clearer and better for testing to have something like
Copy code
fun isTooLate(currentTime: Long = System.currentTimeMillis())
3
r
thanks, this coding-convetions is a very useful link!
yea, i know it can be clearer, i wanted to give an example where the returned value changes over time based on external events