https://kotlinlang.org logo
Title
f

Fudge

12/03/2019, 12:19 AM
Smartcasting a function type property seems to not work.
class Foo(val callback: (() -> Unit)? = null) {
    init {
        if (callback != null) {
            callback() // Error: Reference has a nullable type '(() -> Unit)?'
        }
    }
}
This works fine:
class Foo(callback: (() -> Unit)? = null) {
    init {
        if (callback != null) {
            callback() // Error: Reference has a nullable type '(() -> Unit)?'
        }
    }
}
And this too:
class Foo(val callback: (() -> Unit)? = null) {
    init {
        if (callback != null) {
            callback.invoke()
        }
    }
}
s

streetsofboston

12/03/2019, 1:52 AM
Yup, looks like a bug to me as well. - it's in an init block, no race conditions are possible - it's a immutable
val
, cannot be changed after being set Smart cast should be able to figure that out, and it does in the 3rd example.
e

E.Kisaragi

12/03/2019, 3:13 AM
how will it if check by 'is'?
a

Alexey Belkov [JB]

12/03/2019, 11:40 AM
https://youtrack.jetbrains.com/issue/KT-4113 No smartcast for nullable lambda property (functional type) with implicit/operator
invoke
call
f

Fudge

12/03/2019, 12:47 PM
6 years ago? Wow, this seems like it would be easy to fix though.