IDEA doesn't offer to replace a null check + dot action to `?.`

32 Views Asked by At

I have the following code example below.

Replacing the following null check + dot action

a != null && a.toInt() == b

with ?.

a?.toInt() == b

"seems" to do the same job and even clearer.

But, as you can see in the image, IDEA doesn't suggest the replacement.

Perhaps the two expressions aren't equivalent?

Example code:

fun main() {
    val a: String? = initA()
    val b = 1
    if (a != null && a.toInt() == b) {
        println("true")
    } else {
        println("false")
    }
}

Screencap: enter image description here

1

There are 1 best solutions below

1
AlikElzin-kilaka On

The second I clicked post I understood.

If b's type is changes to nullable, meaning:

val b: Int?

Those expressions cease to be equivalent.

If both a and b are null, the behavior will be different.