Question. Kotlin requests to check nullable membe...
# getting-started
t
Question. Kotlin requests to check nullable member property every time refer to it even it is initialized in same function. Is there a way to avoid this?
Copy code
// I have to copy to local variable
fun menberFunction(){
    var x = this.x
    if( x == null ){
        x = X()
        this.x=x
    }
    codeUsingX(x)
    // this.x may reset to null outside of this function.
}

// I want just using  this.x
fun menberFunction(){
    if( x == null ) x = X()
    codeUsingX(x)
    // this.x may reset to null outside of this function.
}
a
do it this way:
val x = this.x ?: X()
then you have an immutable non-nullable
X
t
it's same thing about using local copy. also I still have to write
Copy code
this.x=x
a
what are you trying to accomplish?
t
don't create local copy, just use this.x.
a
but you need to assign a new value when its
null
and afterwards use it like a non-nullable var?
t
If it is obvious that this.x is not manipulated externally while executing the function, It would be nice to have a way to express it. That way we do not need extra copies or null checks or wrapper function.
a
the compiler is not able to infer that
this.x
isn't manipulated during the execution of the functions
why is
this.x
nullable?
t
this.x may reset to null outside of this function. it may use many system resource.
If the compiler can not handle this problem correctly at this time, we should compromise with local copy
a
yes, the easiest way is to use a local property. I'm curious: What system resources are you using, that you need to be able to go back and forth between
null
and
X()
t
Actually, X will be given different arguments each time it is created. The lifecycle of caller and X is very different. I think that it is reasonable to use Nullable in this case
a
that sounds like you are violating the Single Responsibility Principle
t
I am not interested in your religion.
a
lol
its not about "religion", its about good software design