Kotlin Global Function:
fun Activity.showWarningDialog(title: Int, description: Int,done:()->Unit) {
done()
}
calling this in java:
showWarningDialog(this,R.string.alert,R.string.leave_without_saving,() -> {
setResult(RESULT_CANCELED);
finish();
});
it gives the following error: Cannot resolve method 'showWarningDialog(com.us.stickermaker.backgroundRemover.CutOutActivity, int, int, <lambda expression>)'
the function is imported into the activity file, works fine if we remove the lambda parameter.
CodePudding user response:
Your lambda's type in Kotlin is ()->Unit
, which Java sees as kotlin.Function0<kotlin.Unit>
. So your Java lambda needs to return Unit
instead of void
as it currently does.
showWarningDialog(this, R.string.alert, R.string.leave_without_saving, () -> {
setResult(RESULT_CANCELED);
finish();
return Unit.INSTANCE;
});
should work. The Kotlin compiler inserts returning Unit
for you, but Java doesn't treat Unit
specially in any way.
If you just want to call the function from Java in one or a few places, this may be good enough; otherwise the way to make it convenient to call from Java is fun interface
as shown in Andrii Hridin's answer.
CodePudding user response:
Instead of lambda try to use "fun interface". For example:
fun interface OnWarningDoneListener {
fun onWarningDone()
}
fun Activity.showWarningDialog(title: Int, description: Int, onWarningDoneListener: OnWarningDoneListener) {
onWarningDoneListener.onWarningDone()
}