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?
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.
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.
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.
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() { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With