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

12.3k Views Asked by At

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
1

There are 1 best solutions below

6
Zoe is on strike On BEST ANSWER

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.