Klitos Kyriacou
07/26/2023, 2:20 PMval a: Int = foo()
val b: Int? = bar()
if (a < b!!) {...}
else if (a == b) {...}
else if (a == b + 1) {...}
In the case of a == b it calls Int.equals(Any?) so it boxes a and then compares it to the boxed b. But for a == b + 1 it smart-casts b as Int. Why doesn't it smart-cast b in the first case?Gleb Minaev
07/26/2023, 2:31 PMb!! did not throw any exception then b is Int. Thus, it smarcasts b in a == b + 1 in
if (a < b!!) {} else if (a == b + 1) {}
in the same way as it smartcasts b in a < b in
if (a == b!! + 1) else if (a < b) {}Klitos Kyriacou
07/26/2023, 2:52 PMb because you can can't do the + and < operations on Int? but they can be done on Int and so the smart cast is necessary. But my question is why does it not smart cast b in the expression a == b? It can but chooses not to, and prefers to box a instead of comparing primitives.Gasan
07/26/2023, 4:55 PM+ in (b + 1) is an int, the compiler converts b to int. So the resulting value has the type int. So now you have a == <some int> , so the compiler converts a to intKlitos Kyriacou
07/26/2023, 5:02 PMa is already an Int.Gasan
07/26/2023, 5:04 PMb + 1?Klitos Kyriacou
07/26/2023, 5:06 PMb + 1 is an Int.Klitos Kyriacou
07/26/2023, 5:18 PMa == b does. It's just IntelliJ IDEA says b is not smart-cast, but it seems the compiler does indeed smart-cast it.