Gavriel
Gavriel

Reputation: 19247

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

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?

Upvotes: 3

Views: 2350

Answers (2)

Gavriel
Gavriel

Reputation: 19247

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;}

Upvotes: 4

hotkey
hotkey

Reputation: 148189

I'm not sure that it's exactly why you get that kind of error, but you can try to fix your code by passing a Unit-returning lambda instead of a lambda without a return value:

foo.setOnRefreshListener(() -> { onRefreshStarted(); return Unit.INSTANCE; });

Since the Function0<T> interface's invoke() returns T, when calling a Kotlin method accepting a () -> Unit from Java, you have to pass a lambda that returns Unit.

Upvotes: 3

Related Questions