```fun foo(): String { var local: String? = nu...
# getting-started
u
Copy code
fun foo(): String {
    var local: String? = null
    if (local == null) {
        local = "hello"
    }
    return local // compiler still thinks nullable
}
Why doesn't this smart cast?
r
The compiler cannot account for every path through a program. At that point it would essentially be actually running the program (and often multiple times) in order to calculate all possible types. In terms of theory, this is somewhat similar to the halting problem. I think of it like this: you have static guarantees, and runtime guarantees. Static guarantees are known because of the way the program is structured (if-blocks, val instead of var, etc). These are often easy for the compiler to figure out. Runtime guarantees are known because of what the program actually does within its given structure. These are difficult or impossible for the compiler to know ahead of time. I'd say your example is a case of a runtime guarantee. Try something like this:
Copy code
fun foo(x: String?): String {
    val local = x ?: "hello"
    return local
}
u
I know elvis works, im just trying to see that code above doesnt. Okay so there are hardcoded patterns that the compiler then can assume are okay, thanks
j
The smart casting in your code works for me even in very old compiler versions: https://pl.kotl.in/4d1Iueypx
➕ 2
j
If you return early, does the smart case work?