相关疑难解决方法(0)

如何为 Java 调用者声明一个返回类型为“void”的 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方法?

java kotlin

5
推荐指数
1
解决办法
2962
查看次数

标签 统计

java ×1

kotlin ×1