https://kotlinlang.org logo
Title
t

tateisu

01/31/2018, 11:10 AM
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?
// 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

Andreas Sinz

01/31/2018, 11:16 AM
do it this way:
val x = this.x ?: X()
then you have an immutable non-nullable
X
t

tateisu

01/31/2018, 11:17 AM
it's same thing about using local copy. also I still have to write
this.x=x
a

Andreas Sinz

01/31/2018, 11:18 AM
what are you trying to accomplish?
t

tateisu

01/31/2018, 11:20 AM
don't create local copy, just use this.x.
a

Andreas Sinz

01/31/2018, 11:22 AM
but you need to assign a new value when its
null
and afterwards use it like a non-nullable var?
t

tateisu

01/31/2018, 11:26 AM
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

Andreas Sinz

01/31/2018, 11:37 AM
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

tateisu

01/31/2018, 11:38 AM
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

Andreas Sinz

01/31/2018, 11:44 AM
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

tateisu

01/31/2018, 11:55 AM
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

Andreas Sinz

01/31/2018, 1:40 PM
that sounds like you are violating the Single Responsibility Principle
t

tateisu

02/01/2018, 6:12 AM
I am not interested in your religion.
a

Andreas Sinz

02/01/2018, 7:51 AM
lol
its not about "religion", its about good software design