What's the best way to deal with nullability of a object's variable? To indicate that I know that the variable's value won't change during the execution of a function, because the class is used in a single thread, single coroutine, so if I tested the value and ensured it's non-null, it can't be set to null during the execution of the function? Let me give an example
class C(private var v: Int?) {
fun p(i: Int) = print(i)
fun f() {
if (v != null) {
p(v!!)
}
}
}
(A more realistic code example is given at the end of the question)
I know that C is always executed in a single thread. So there is no way that v's value change while f is executing. Hence there is no way that v can become null, thus v!! is useless.
Even
fun f() {
synchronized(this) {
if (v != null) {
p(v!!)
}
}
}
requires the !! (not that I would want to use it, given the cost of synchronization.
So my question is, what is the Kotlin way to solve this issue? I can think of at least three solutions.
fun f_local() {
val v = v ?: return
p(v)
}
Not great because it adds a line whose content has little value. Even if (v==null) return would at least be more clear about the actual meaning.
Also, would not work if we had things to do when v is null/independently of v
fun f_inside_return() {
p(v?: return)
}
This does not seems very readable. And if we used v multiple time, we need to repeat ?: return multiple time.
fun f_let() = v?.let(::p)
fun f_let_2() = v?.let{v -> p(v)}
This one seems to make sens in Kotlin. But if we have to deal with multiple nullable variable, that means we are getting many scoped functions once inside the other, which is far from great.
=================
In a more realistic example, my code would contains something such as
fun h() { v = v +1 ?: 0 }
fun f() {
if (v != null) {
p(v!!)
p_(v!!)
} else {
print("no v")
}
print("done")
}
so v is used multiple time, and some code is executed if v is null and some code is executed whatever is the value of v. And since h is not called in f, the value of v can't be changed even if v needs to be var