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

Chriss :

I have a library that is completely written in Kotlin including its public 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. The effect is that the Java side has always to return Unit.INSTANCE for methods that are effectivly void. Can this be avoided somehow?

Example:

Kotlin interface

interface Foo{
  fun bar()
}

Java implementation

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?

Roland :

Both Void and void work, you just need to skip that Unit...

Kotlin interface:

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

Java class implementing that interface:

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:

This type corresponds to the void type in Java.

And as we know, the following two are equivalent:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99537&siteId=1