Kotlinfunction:需要的单位? findInt

在Kotlin反复面对这个问题

fun test(){ compute { foo -> Log.e("kotlin issue", "solved") } // This line is //showing error } fun compute(body: (foo:String) -> Unit?){ body.invoke("problem solved") } 

我在Studio中遇到错误。 这是一个截图。 在这里输入图像说明

你传递给compute函数的lambda必须返回Unit? 。 现在,您将返回Log.e()调用的结果,该调用返回一个Int表示写入输出的字节数。 如果你想要做的只是在lambda中记录一条消息,你可以在它的结尾明确地返回Unit

 fun test() { compute { foo -> Log.e("kotlin issue", "solved") Unit } } 

另外,看看这个问题在哪里转换返回值为Unit其他方式讨论。

Android Log.e返回Int ,其中body参数指定返回types应为Unit?

您需要更改compute方法签名,如下所示:

 fun compute(body: (foo: String) -> Unit) { body.invoke("problem solved") } 

或者像这样改变调用:

 compute { foo -> Log.e("kotlin issue", "solved"); null } 

或者换一个计算来改变调用:

 fun myCompute(body: (foo: String) -> Any?) { compute { body(it); null } } 

然后按照您的预期调用它:

 myCompute { foo -> Log.e("kotlin issue", "solved") }