It seems like the compiler's null tracking doesn't...
# announcements
p
It seems like the compiler's null tracking doesn't work when the type of the variable is a function and the variable is an instance variable on a class.
Copy code
fun thing(a: ((String) -> String)?) {
    if (a == null) {
        println("null")
    } else {
    	println(a("hello"))
    }
}

class Thing(private val a: ((String) -> String)?) {
    fun thing() {
        if (a == null) {
            println("null")
        } else {
            // Reference has a nullable type '((String) -> String)?', use explicit '?.invoke()' to make a function-like call instead
        	println(a("hello"))
        }
    }
}
Reproducing the issue using the playground
m
that's because
a
is a function and every call to that function can produce a new value.
mhh goes deeper than that, disregard my statement
p
Correct, this is about trying to call the function, not act on the result.
The issue does have something to do with the type being a function. Here is the same example tweaked to use a data class instead and it works as expected.
k
What if you use
.invoke
instead of calling?
p
Using
.invoke()
does work.
So that can be a workaround I use for now. But it is not clear why the syntactic sugar doesn't work in this case when it works for a function.
This is apparently a known issue.