kotlin - 为什么必须用invoke调用类成员函数类型?

标签 kotlin

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

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

上面的代码产生了错误:

Kotlin: Reference has a nullable type '((Double, Double) -> DoubleArray)?', use explicit '?.invoke()' to make a function-like call instead.

如果我遵循错误建议并将调用更改为 test.foo?.invoke(1.0, 2.0),代码会编译,但 IntelliJ 现在会报告

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

根据该建议,我最终得到了 test.foo.invoke(1.0, 2.0),我认为它可以与 test.foo(1.0, 2.0); 互换;为什么这里不是这样?

当 foo 不是类成员时,事情会按我的预期工作:

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

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

最佳答案

有一个 Unresolved 问题:https://youtrack.jetbrains.com/issue/KT-4113

目前,它的目标版本是 1.3。

关于kotlin - 为什么必须用invoke调用类成员函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157172/

相关文章:

android - 智能转换为 (Int) 是不可能的,因为 <variable> 是一个局部变量,由变化的闭包捕获

android - 通过命令行运行时,库中的Android非仪表测试失败。/gradlewclean {library_name}:testDebugUnitTest

android - GenericClass 不支持 Class<float>

android - Kotlin 三元运算符

安卓动态特性 : Error -2 Module Unavailable

android - 保存位图 Android 8 时图像名称和类型错误

intellij-idea - IntelliJ 中的 Kotlin Unresolved reference

java - Android DecimalFormat 格式不正确

kotlin - android jetpack compose 中带有 ConstraintLayout 的 LazyColumn

gradle - Gradle Kotlin DSL 中的 kotlin ("...") 方法是什么?