Search code examples
kotlinkotlin-null-safety

Null Safety on IF comparison in Kotlin


I have a question about how Kotlin manages NULL safety on comparison. I have this code:

imageFile.addListener { _ , oldValue : File?, newValue : File? ->
    run{
        if(oldValue?.absolutePath != newValue?.absolutePath) loadFile()
    }
}

It works fine, however if I change it to

imageFile.addListener { _ , oldValue : File?, newValue : File? ->
    run{
        if(oldValue!!.absolutePath != newValue?.absolutePath) loadFile()
    }
}

It throws a NullPointerException and that's obvious, because when the application starts oldValue is NULL.

How Kotlin manages this comparison the first time?

Thanks for your help.


Solution

  • You are using safe call which avoid NullPointerException:

    option is the safe call operator, written ?.

    returns null if any of the properties in it is null.

    Second option not-null assertion operator throws exception

    The !! Operator

    the not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null