If I pass a method reference from Java to a Kotlin...
# announcements
t
If I pass a method reference from Java to a Kotlin function, what do I put for parameter type? E.g.
Copy code
MyJavaClass {
  MyKotlinClass myKotlinClass;

  void myMethod() { ... }

  ... myKotlinClass.foo(this::myMethod);
}
What should be the parameter in
fun foo( ? )
?
d
You can just use a normal Kotlin function, as they are a "functional interface" from Java's point of view. If you however need
void
as a return type, you need to use something like
Runnable
or
Consumer
from
java.util.function
or make your own functional interface.
e
My guess is it would be either
() -> Unit
or
() -> Nothing
I can verify later if you like
d
() -> Unit
requires you to do
return kotlin.Unit.getINSTANCE()
(or something) from Java
s
It won’t be
() -> Nothing
. This type is a function/lambda that never returns normally (either it loops forever or it always throws an exception).
t
When I tried
() -> Unit
I had to do weird stuff in my Java function like
return Unit.INSTANCE
For now I created a single function interface in the kotlin class and am using that as the parameter type. This compiles. But open to any improvements