【问题标题】:How to declare a Kotlin function with return type 'void' for a java caller?如何为 Java 调用者声明返回类型为“void”的 Kotlin 函数?
【发布时间】:2018-12-06 13:19:41
【问题描述】:

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

例子:

Kotlin 界面

interface Foo{
  fun bar()
}

Java 实现

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

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

【问题讨论】:

标签: java kotlin


【解决方案1】:

Voidvoid 都有效,您只需跳过 Unit...

Kotlin 界面:

interface Demo {
  fun demoingVoid() : Void?
  fun demoingvoid()
}

实现该接口的 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...

    }
}

请注意,虽然Kotlins reference guide 'Calling Kotlin from Java' 没有真正提及它,但Unit documentation 确实:

这个类型对应Java中的void类型。

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

fun demo() : Unit { }
fun demo() { }

【讨论】:

【解决方案2】:

我使用 java 接口实现了一个简单的变体。

--- 在 ACallback.java 中 --

public interface ACallback<T> {
     void invoke( T data );
}

-- 在 Kotlin 文件中

fun dostuff( arg: String , callback: ACallback<String> ) { 
   stuff();
   callback(arg) ; // yes 'invoke' from java 
}

---在java中----

  doStuff( "stuff" , ( String arg) -> voidReturningFunction( arg ) ) ;

【讨论】:

    【解决方案3】:

    示例:

    override fun doInBackground(vararg params: Void?):Void{
        for (i in 0 until 10) {
    
            Thread.sleep(1000);
        }
    
        return null as Void;
    
    }
    

    【讨论】:

    • 虽然这段代码可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多