如何为 Java 调用者声明一个返回类型为“void”的 Kotlin 函数?

Chr*_*iss 5 java kotlin

我有一个完全用 Kotlin 编写的库,包括其公共 API。现在库的用户使用 Java,这里的问题是具有返回类型的 Kotlin 函数Unit没有编译为返回类型void。结果是 Java 端必须始终为有效无效的方法返回 Unit.INSTANCE。这可以以某种方式避免吗?

例子:

Kotlin 接口

interface Foo{
  fun bar()
}
Run Code Online (Sandbox Code Playgroud)

Java实现

class FooImpl implements Foo{
   // should be public void bar()
   public Unit bar(){  
      return Unit.INSTANCE 
      // ^^ implementations should not be forced to return anything 
   }
}
Run Code Online (Sandbox Code Playgroud)

是否可以以不同方式声明 Kotlin 函数以便编译器生成voidorVoid方法?

Rol*_*and 7

两者Voidvoid可以工作,你只需要跳过它Unit......

科特林接口:

interface Demo {
  fun demoingVoid() : Void?
  fun demoingvoid()
}
Run Code Online (Sandbox Code Playgroud)

实现该接口的 Java 类:

class DemoClass implements Demo {

    @Override
    public Void demoingVoid() {
        return null; // but if I got you correctly you rather want to omit such return values... so lookup the next instead...
    }

    @Override
    public void demoingvoid() { // no Unit required...

    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,虽然Kotlins 参考指南“从 Java 调用 Kotlin”并没有真正提到它,但Unit文档确实提到了:

该类型对应于voidJava中的类型。

众所周知,以下两个是等效的:

fun demo() : Unit { }
fun demo() { }
Run Code Online (Sandbox Code Playgroud)