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") }