15

I have a Kotlin Code:

fun showAdWithCallback(callback:() -> Unit) {
    if (AdsPrefs.shouldShowInterstitialAd()) {
        mInterstitialAd.show()
        this.callback = callback
    } else {
        callback()
    }
}

Now I want to call this method from a Java Class. I am confused about how to call this. Here is what I tried

  showAdWithCallback(() -> {
        return null;
    });

But it shows following error.

enter image description here

Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63
  • how about https://stackoverflow.com/questions/37828790/why-do-i-have-to-return-unit-instance-when-implementing-in-java-a-kotlin-functio – P.Juni Jul 30 '19 at 07:02
  • Check out here https://stackoverflow.com/questions/16120697/kotlin-how-to-pass-a-function-as-parameter-to-another – Vipul Prajapati Jul 30 '19 at 07:07
  • @P.Juni The reference you gave has a callback that accept one argument, but I have a callback without any parameters. So that doesn't solve the problem. – Prajeet Shrestha Jul 30 '19 at 07:10
  • @VipulPrajapati The reference you gave has examples of passing function from a kotlin code to kotlin functions, what I want here is to let my java class use function in kotlin class (which accepts function as a argument) – Prajeet Shrestha Jul 30 '19 at 07:13
  • https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java – P.Juni Jul 30 '19 at 07:15
  • 2
    @PrajeetShrestha please share the code before your `showAdWithCallback` – Bartek Lipinski Jul 30 '19 at 07:15
  • 1
    @BartekLipinski. Oh u got me........I had return statement just before showAdWithCallback. I was randomly embedding showAdWithCallback to tryout, overlooked the return statement. Thank u so much. You can put it as a answer I will accept and upvote. – Prajeet Shrestha Jul 30 '19 at 07:24

3 Answers3

13

The error message is caused by the code before your:

showAdWithCallback(() -> {
        return null;
});
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
1

Call kotlin object and call function

kotlinobject.INSTANCE.showAdWithCallback(()->{
    return null;
})
Yogesh Bangar
  • 480
  • 4
  • 12
0

callback:() -> Unit

It's a typically runnable - zero arguments, without return value

tragos777
  • 1
  • 1