Why should calls be called using a class class call?

fun test() {
    class Test(val foo: ((Double, Double) -> Double)?)
    val test = Test(null)

    if(test.foo != null) test.foo(1.0, 2.0)
}

The code above generates an error:

Kotlin: Reference has type with null value '((Double, Double) -> DoubleArray)? ', Use explicit'?. Invoke () 'to make a function call instead.

If I follow the error tips and change the call to test.foo?.invoke(1.0, 2.0), the code compiles, but IntelliJ now reports

Unnecessary safe call to a non-empty receiver of type '((Double, Double) -> DoubleArray)

Following this advice, I end with test.foo.invoke(1.0, 2.0), which I thought was interchangeable with test.foo(1.0, 2.0); why is this not so?

When foo is not a member of the class, everything works as I expected:

fun test2() {
    val foo: ((Double, Double) -> Double)? = null

    if(foo != null) foo(1.0, 2.0)
}
+6
source share
2 answers

, , , , . invoke():

enter image description here

let :

test.foo?.let { foo ->
    foo(1.0, 2.0)
}
+1

All Articles