0

我创建了一个函数,它应该获取一个挂起的函数作为它的参数,运行它,并对结果执行一些操作。

当我尝试调用此函数并传递来自不同类的函数引用时(例如,我们称其为“SomeClass”),我在 intellij 上看到以下错误:

Type mismatch.

Required:
suspend (String, Int) → SomeType

Found:
KSuspendFunction3<OtherClass, String, Int, SomeType>

我的函数应该获得一个挂起的函数作为参数:

private suspend fun performSomeOperation(
    block: suspend (String, Int) -> SomeType
) : Result<SomeValue> {
    .
    .
    .
}

我从“OtherClass”引用的函数

suspend fun performOperation(id: String, value: Int): SomeType {
    .
    .
    .
}

对我的函数的调用,将OtherClass::performSomeOperation函数引用作为参数传递

updateRestartParam(OtherClass::performSomeOperation)
4

2 回答 2

1

警告消息的语法对描述它找到的参数没有帮助。OtherClass::performSomeOperation真的是类型

suspend (OtherClass, String, Int) -> SomeType

或者

suspend OtherClass.(String, Int) -> SomeType

当作为函数参数传递时,它们被同等对待。如您所见,otherClassInstance::performSomeOperation具有您需要的类型。通过指定实例,它被绑定到函数,因此它不是它的参数之一。

于 2021-07-25T14:54:02.013 回答
1

好的,所以看起来这个错误是因为我试图传递一个“Bound Callabele Reference”,这意味着引用不同类的成员函数。

从 Kotlin 1.1 开始,您可以通过在函数引用运算符前面加上实例来做到这一点:

updateRestartParam(otherClassInstance::performSomeOperation)
于 2021-07-25T13:21:16.953 回答