https://kotlinlang.org logo
Title
c

CLOVIS

04/07/2023, 3:31 PM
Wow, I just learned smart-casting doesn't require a lexical scope:
data class Foo(val a: Int)

val a: Foo? = null

val b = a
    ?.copy(a = a.a+1) // a is smart-casted here!
    ?: Foo(0)

println(b)
I thought it wasn't possible without using `let`&co. Playground link.
p

Pablichjenkov

04/07/2023, 4:09 PM
Not sure if that has to do with smart casting but the fact that if you omit the type nullability, the compiler will infer it from the statement. And in this case is clear b won't be null ever
y

Youssef Shoaib [MOD]

04/08/2023, 9:32 PM
Happens as well if you cast something previously in scope:
fun Foo.foo(){
  this as Bar
  barFunction()
}