Repeatedly facing this issue in 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")
}
I am getting the error in Studio. Here is a screenshot.
The lambda you pass to the compute
function has to return Unit?
. Right now, you're returning the result of the Log.e()
call, which returns an Int
representing the number of bytes written to the output. If all you want to do is log a message in the lambda, you can explicitly return Unit
at the end of the it like so:
fun test() {
compute { foo ->
Log.e("kotlin issue", "solved")
Unit
}
}
Also, see this question where other means of converting a return value to Unit
are discussed.
Android Log.e
returns Int
where as the body
parameter specifies that the return type should be Unit?
.
You need to either change compute
method signature like so:
fun compute(body: (foo: String) -> Unit) { body.invoke("problem solved") }
Or change the invocation like so:
compute { foo -> Log.e("kotlin issue", "solved"); null }
Or wrap the compute to change the invocation:
fun myCompute(body: (foo: String) -> Any?) { compute { body(it); null } }
and then invoke it as you expect:
myCompute { foo -> Log.e("kotlin issue", "solved") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With