[英]“Function0 is not a functional interface” error when passing java lambda to kotlin fun
This is my kotlin code: 这是我的kotlin代码:
class Foo : Bar {
override var onRefreshListener: (() -> Unit)? = null
...
}
And this is what I try to do in java: 这就是我在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: 在问题()的两种情况下,我从Android Studio收到以下错误:
Function0 is not a functional interface Function0不是功能接口
How can I set the onRefreshListener from java? 如何从java设置onRefreshListener?
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: 我不确定这究竟是为什么你会遇到这种错误,但你可以尝试通过传递一个Unit
返回lambda而不是一个没有返回值的lambda来修复你的代码:
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
. 由于Function0<T>
接口的invoke()
返回T
,因此在调用Kotlin方法从Java接受() -> Unit
时,必须传递一个返回Unit
的lambda。
After fixing the kotlin lib's dependencies in the pom file, here are the 3 possible solutions I could figure out. 在将potlin lib的依赖关系修复到pom文件之后,这里有3个可能的解决方案。
1st solution : No need for kotlin-stdlib in the java project: 第一个解决方案 :在java项目中不需要kotlin-stdlib:
In kotlin add: 在kotlin添加:
@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. 第二个解决方案 :(感谢@hotkey)需要kotlin-stdlib,kotlin代码没有变化。 In java change: 在java中更改:
foo.setOnRefreshListener(() -> onRefreshStarted());
to: 至:
foo.setOnRefreshListener(() -> { onRefreshStarted(); return Unit.INSTANCE; });
3rd solution : needs kotlin-stdlib, no change in kotlin, change: 第3个解决方案 :需要kotlin-stdlib,kotlin没有变化,改变:
private void onRefreshStarted() {}
to: 至:
private Unit onRefreshStarted() {...; return null;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.