https://kotlinlang.org logo
Title
t

tenprint

07/26/2019, 2:03 PM
If I pass a method reference from Java to a Kotlin function, what do I put for parameter type? E.g.
MyJavaClass {
  MyKotlinClass myKotlinClass;

  void myMethod() { ... }

  ... myKotlinClass.foo(this::myMethod);
}
What should be the parameter in
fun foo( ? )
?
d

diesieben07

07/26/2019, 2:08 PM
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

Evan R.

07/26/2019, 2:40 PM
My guess is it would be either
() -> Unit
or
() -> Nothing
I can verify later if you like
d

diesieben07

07/26/2019, 2:41 PM
() -> Unit
requires you to do
return kotlin.Unit.getINSTANCE()
(or something) from Java
s

streetsofboston

07/26/2019, 3:17 PM
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

tenprint

07/26/2019, 3:28 PM
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