Home > Net >  Consuming a Kotlin Function with an Argument in a Java file using the correct syntax
Consuming a Kotlin Function with an Argument in a Java file using the correct syntax

Time:07-05

I have a variable called onItemSelected in a Kotlin file

   var onItemSelected: ((String) -> Void)? = null

In a Java file I am trying to set that variable, but am unable to figure out the correct syntax.

The lambda expression keeps wanting to return a Void, however, when I return a void, then it doesn't compile.

    binding.myCustomView.getOnItemSelected() = (item, Void) -> {
        //What should happen here?
        Log.i("Test", item);
        return;
    };

I have tried various syntax, but I can't seem to get it correct.

What is the proper way to set a variable with a function that has an argument?

CodePudding user response:

In Kotlin, a function that doesn't return a value should return Unit, not java.lang.Void. In fact, this is true in Java too - in Java you should return void, not java.lang.Void.

So change the Kotlin code to:

var onItemSelected: ((String) -> Unit)? = null

Now in the Java code, you need to return kotlin.Unit.INSTANCE, because that is the only instance of Unit there exists (Unit is declared as an object). Returning Unit.INSTANCE is implicit if you are doing this in Kotlin, but you need to do this explicitly in Java.

import kotlin.Unit;

// ...

binding.setOnItemSelected(item -> {
    System.out.println(item);
    // do your thing with item...
    return Unit.INSTANCE;
});
  • Related