简体   繁体   English

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

[英]How to declare a Kotlin function with return type 'void' for a java caller?

I have a library that is completely written in Kotlin including its public API.我有一个完全用 Kotlin 编写的库,包括它的公共 API。 Now a user of the library uses Java, the problem here is that Kotlin functions with return type Unit are not compiled to return type void .现在该库的用户使用 Java,这里的问题是具有返回类型Unit的 Kotlin 函数未编译为返回类型void The effect is that the Java side has always to return Unit.INSTANCE for methods that are effectivly void.结果是 Java 端必须始终为实际上无效的方法返回 Unit.INSTANCE。 Can this be avoided somehow?这可以以某种方式避免吗?

Example:例子:

Kotlin interface科特林界面

interface Foo{
  fun bar()
}

Java implementation Java实现

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

Is it possible to declare the Kotlin function differently so the compiler generates a void or Void method?是否可以以不同方式声明 Kotlin 函数,以便编译器生成voidVoid方法?

Both Void and void work, you just need to skip that Unit ... Voidvoid都工作,你只需要跳过那个Unit ...

Kotlin interface:科特林界面:

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

Java class implementing that interface:实现该接口的 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...

    }
}

Note that while Kotlins reference guide 'Calling Kotlin from Java' does not really mention it, the Unit documentation does:请注意,虽然Kotlin 参考指南“从 Java 调用 Kotlin”并没有真正提到它,但Unit文档确实提到了:

This type corresponds to the void type in Java.该类型对应Java中的void类型。

And as we know, the following two are equivalent:正如我们所知,以下两个是等价的:

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

I implemented a simple variant on this using a java interface.我使用 java 接口对此实现了一个简单的变体。

--- In ACallback.java -- --- 在 ACallback.java 中 --

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

-- In a Kotlin file -- 在 Kotlin 文件中

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

--- In java ---- --- 在 Java 中 ----

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

example:例子:

override fun doInBackground(vararg params: Void?):Void{
    for (i in 0 until 10) {

        Thread.sleep(1000);
    }

    return null as Void;

}

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

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