Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass function as parameter from java to kotlin method?

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

like image 523
Prajeet Shrestha Avatar asked Jul 30 '19 07:07

Prajeet Shrestha


People also ask

Can you pass a function as a parameter in Kotlin?

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with.

How does Kotlin return a function from another function?

To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.

Can Java and Kotlin work together?

If your question is can you use kotlin files in java files and vice versa then the answer is yes.

How do you pass a method as a parameter in Java?

We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .


1 Answers

The error message is caused by the code before your:

showAdWithCallback(() -> {
        return null;
});
like image 166
Bartek Lipinski Avatar answered Oct 18 '22 08:10

Bartek Lipinski