作为绑定适配器的高阶函数的问题 [英] Issue with higher order function as a binding adapter
问题描述
我在尝试使用Kotlin/Android数据绑定在绑定适配器中将函数用作参数时遇到问题.如果在日志中没有其他有用信息的情况下进行构建,则此示例代码将引发e: error: cannot generate view binders java.lang.StackOverflowError
.
I am running into issues trying to take a function as a parameter in a binding adapter using Kotlin/Android databinding. This example code throws e: error: cannot generate view binders java.lang.StackOverflowError
when building with no other useful info in the log.
这是我的绑定适配器:
@JvmStatic
@BindingAdapter("onDelayedClick")
fun onDelayedClick(view: View, function: () -> Unit) {
// TODO: Do something
}
XML:
<View
android:id="@+id/test_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:onDelayedClick="@{() -> viewModel.testFunction()}"/>
和ViewModel中的方法:
and method in my ViewModel:
fun testFunction() = Unit
我已经为此苦苦挣扎了一段时间,但我没有尝试过,因此可以提供任何帮助.
I have been struggling with this for a bit now and nothing I've tried works, so any help is appreciated.
推荐答案
使用function: Runnable
代替function: () -> Unit
.
Android的数据绑定编译器会生成Java代码,您的kotlin函数的签名类似于void testFunction()
,因为kotlin在从Java调用时会将Unit调整为void.
Android's data-binding compiler generates java code, to which, your kotlin function's signature looks like void testFunction()
, as kotlin adapts Unit as void when calling from java.
另一方面,() -> Unit
看起来像kotlin.jvm.functions.Function0
,该函数需要0个输入并返回Unit.INSTANCE.
On the other hand, () -> Unit
looks like kotlin.jvm.functions.Function0
which is a function which takes 0 inputs and returns Unit.INSTANCE.
如您所见,这两个函数签名不匹配,这就是编译失败的原因.
As you can see these two function signatures don't match, and that's why the compilation fails.
这篇关于作为绑定适配器的高阶函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!