``` val x : Int? = 5 // x!! // if uncomment this ...
# compiler
p
Copy code
val x : Int? = 5
 // x!! // if uncomment this line there will be no compilation error  
 x + 1 // compilation error as x treated as nullable. I think compiler can 'smart cast' it from initial assignment
d
It was done intentionally, because otherwise there would be no way to opt-out from this smartcast. So the rule is following: smartcasts are inferred from rhs of the
=
only in case of variable assignment, not the variable initialization.
Copy code
fun main() {
    val x : Int?
    x = 5
    x + 1 // smartcasted
}
p
While trying to check with var faced with strange thing:
Copy code
@Test
    fun test() {
        var x : Int? = 5
        x!!
        x + 1
        x = null
        val y = x + 1 // treat y as String // why?
        println(y) // print null1
    }
d
x
smartcasted to
Nothing?
+
resolved to
operator fun String?.plus(other: Any?): String
from stdlib
p
But why Nothing? resolved to String? ?
d
Because
Nothing?
is subtype of
String?
thank you color 1