简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM