Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin passing function as argument got Type mismatch, Required: ()->Unit, Found: Unit

Having a function which takes function type for the callback

fun dataBtnClickHandler(callbackFunc: () -> Unit){

    // do something
    ......

    // call the callback function
    callbackFunc     
}

And there is a function defined as

private fun lunchStartActivity() {
    val intent = Intent(this, StartActivity::class.java)
    val bundle = Bundle()
    bundle.putInt(FRAGMENT_PREFERENCE, fragmentPreference)
    intent.putExtras(bundle)
    startActivity(intent)
}

in the click switch it call the dataBtnClickHandler and passing the lunchStartActivity() for the callback.

But it gets error: Type mismatch, Required: ()->Unit, Found: Unit, what does the error mean?

when (clickedId) {
   R.id.data_btn -> dataBtnClickHandler(lunchStartActivity())  //<=== Error:  Type mismatch, Required: ()->Unit, Found: Unit
like image 240
lannyf Avatar asked Dec 14 '22 14:12

lannyf


1 Answers

Your method expects a function argument that returns unit.

callbackFunc: // Name with a type that is
    () // a 0 arg function
    -> Unit // that returns Unit (AKA void, or nothing) 

If you pass the method call directly, you give the method an argument that consists of the return type. The way you originally did would pass Unit to the method.

To pass an actual method, and not just the return type from a call, as an argument, you use :::

dataBtnClickHandler(::launchStartActivity)

Alternatively this::launchStartActivity if it's in the current object/class, or replace this with a class name (or file name if it's a top-level function). Though :: works in most cases.

Remember; you're passing a method reference here, not the result of a method call, or a variable.

like image 143
Zoe stands with Ukraine Avatar answered Dec 18 '22 00:12

Zoe stands with Ukraine