0

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.

Usama Saeed US
  • 984
  • 11
  • 18
  • 1
    Maybe I'm missing something about how Kotlin methods are compiled, but your Kotlin method has 3 parameters, you're passing 4 parameters in your Java call – Jeroen Steenbeeke Sep 16 '21 at 07:39
  • look closely, when a kotlin extension function is called in java, the "object" would be passed as a parameter in this case its an activity. – Usama Saeed US Sep 16 '21 at 07:41
  • I see. I did a bit of reading on the subject, and from what I've read in [this answer](https://stackoverflow.com/a/28364983/8819761), you would need to prefix your method with the the filename it was declared in. – Jeroen Steenbeeke Sep 16 '21 at 08:45
  • As i told in the question, if i remove the lambda, it works fine in java, and yes function is imported with the file name. – Usama Saeed US Sep 16 '21 at 11:37

2 Answers2

2

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
-1

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()
}