Can I call this Kotlin method from Java?
fun foo(() -> Unit)
If so, what's the syntax?
You need to create instance of Function0:
foo(new Function0<Unit>() {
@Override
public Unit invoke() {
// Here should be a code you need
return null;
}
});
or if you use Java 8 it can be simplified
foo(() -> {
// Here should be a code you need
return null;
});
You can call this but need to be careful of the return types. If your Kotlin function returns a Unit, Java will either need to return Unit or null, because void is not quite the same as Unit.
My example that worked:
foo(() -> {
System.out.println("Hi");
return null;
});
Or, if you want to be really explicit about Unit...
foo(() -> {
System.out.println("Hi");
return Unit.INSTANCE;
});
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