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
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.
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