This is my kotlin code:
class Foo : Bar {
override var onRefreshListener: (() -> Unit)? = null
...
}
And this is what I try to do in java:
class A {
private Foo foo;
private void onRefreshStarted() {}
private void problem() {
foo.setOnRefreshListener(this::onRefreshStarted);
foo.setOnRefreshListener(() -> onRefreshStarted());
}
}
In both cases in problem() I get the following error from Android Studio:
Function0 is not a functional interface
How can I set the onRefreshListener from java?
After fixing the kotlin lib's dependencies in the pom file, here are the 3 possible solutions I could figure out.
1st solution: No need for kotlin-stdlib in the java project:
In kotlin add:
@FunctionalInterface
interface OnRefreshListener {
fun onRefresh()
}
And change the interface from:
var onRefreshListener: (() -> Unit)?
to:
var onRefreshListener: OnRefreshListener?
and the invocations from:
onRefreshListener?.invoke()
to:
onRefreshListener?.onRefresh()
2nd solution: (Thanks to @hotkey) needs the kotlin-stdlib, no change in kotlin code. In java change:
foo.setOnRefreshListener(() -> onRefreshStarted());
to:
foo.setOnRefreshListener(() -> { onRefreshStarted(); return Unit.INSTANCE; });
3rd solution: needs kotlin-stdlib, no change in kotlin, change:
private void onRefreshStarted() {}
to:
private Unit onRefreshStarted() {...; return null;}
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