Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin function: Required Unit? Found Int

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. enter image description here

like image 674
Debanjan Avatar asked Dec 13 '22 19:12

Debanjan


2 Answers

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.

like image 69
zsmb13 Avatar answered Jan 03 '23 04:01

zsmb13


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") }
like image 30
miensol Avatar answered Jan 03 '23 04:01

miensol