Search code examples
kotlinandroid-jetpack-composenull-check

if-statement null-check not working in Kotlin, why?


As shown in below, in debug, if-statement with null-check is entered even though the variable "result" is null. enter image description here Blue line is the line next to be executed. So if-has been entered.

This is how "result" is initialized: var result: Double? = null

"result" is updated in a TextField composables onValueChange function and set to null in onValueChange, before the if-statement with nullcheck. Something like: enter image description here

I can't understand why the if-statements null-check doesn't work.

Any clues anyone?

The if-statement is entered if "result" is not null also.


Solution

  • Kotlin is null safe language so basically what happens in your code is that lets say in the moment T0 we have result != Null but in the moment T1 when inside of the If block is going to be executed another function or line of code in another thread or something has changed result = null then what happens even though the if condition has been passed successfully now the result is null and will cause an error.

    Kotlin introduced a solution with the Let keyword so basically instead of having:

    If(result != Null){
    //Do something
    }
    

    You have to use:

    result?.let{nonNullResult->
    //Do something with this nonNullResult
    }
    

    As you can see when you use the let keyword what happens is kotlin takes a copy of that variable at that specific time when the line is executed if the copy is null the inside block of let will not be executed else if the copy is not null then the Let block will be executed with that non null copy.