Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Function0 is not a functional interface" error when passing java lambda to kotlin fun

Tags:

java

kotlin

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?

like image 667
Gavriel Avatar asked Apr 23 '26 04:04

Gavriel


1 Answers

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;}
like image 59
Gavriel Avatar answered Apr 25 '26 17:04

Gavriel