简体   繁体   English

使用正确的语法在 Java 文件中使用带有参数的 Kotlin Function

[英]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我在Kotlin文件中有一个名为onItemSelected的变量

   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.Java文件中,我试图设置该变量,但无法找出正确的语法。

The lambda expression keeps wanting to return a Void, however, when I return a void, then it doesn't compile. lambda 表达式一直想要返回一个 Void,但是,当我返回一个 void 时,它就无法编译。

    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?使用具有参数的 function 设置变量的正确方法是什么?

In Kotlin, a function that doesn't return a value should return Unit , not java.lang.Void .在 Kotlin 中,不返回值的函数应该返回Unit ,而不是java.lang.Void In fact, this is true in Java too - in Java you should return void , not java.lang.Void .事实上,在 Java 中也是如此——在 Java 中你应该返回void ,而不是java.lang.Void

So change the Kotlin code to:因此将 Kotlin 代码更改为:

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 ).现在在 Java 代码中,您需要返回kotlin.Unit.INSTANCE ,因为这是存在的唯一Unit实例( Unit被声明为object )。 Returning Unit.INSTANCE is implicit if you are doing this in Kotlin, but you need to do this explicitly in Java.如果您在 Kotlin 中执行此操作,则返回Unit.INSTANCE是隐式的,但您需要在 Java 中显式执行此操作。

import kotlin.Unit;

// ...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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