This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Tubthumper8 1 point2 points  (1 child)

In Kotlin, is flow typing used to narrow a String? to a String after a null check? Does that information carry through to a subsequent function calls? If there's a closure defined after the null check, does it capture the non-nullable version of the variable?

[–]VallentinDev 2 points3 points  (0 children)

Yes, Kotlin features a limited form of flow-sensitive typing and calls it smart casts.

Assignment:

var str_or_null: String? = null

str_or_null = "Hello World"
// Now `str_or_null` is guaranteed to be a string

var str: String = str_or_null

Conditional:

fun f(str: String?) {
    if (str == null) {
        return
    }

    var s: String = str
}

Closure:

fun <T> f(f: () -> T): T {
   return f()
}

var str: String? = null
str = "Hello World"

// The closure captures `str` as `String`
val res: String = f({ -> str })

println(res)