Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

kotlin

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?

like image 498
Chriss Avatar asked Dec 06 '18 13:12

Chriss


People also ask

How do you write a void function in Kotlin?

Unit in KotlinBy default, Java void is mapped to Unit type in Kotlin. This means that any method that returns void in Java when called from Kotlin will return Unit — for example the System. out. println() function.

How do I specify return type in Kotlin?

Kotlin function return valuesTo return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.

Can I use return for a method of the return type void?

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.


1 Answers

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() { }
like image 171
Roland Avatar answered Oct 02 '22 23:10

Roland