问题描述
我有一个Java类函数,如下所示
I have a Java Class function as below
public void setPositiveButton(int resId, DialogInterface.OnClickListener listener)
我也有同样的Kotlin Class功能,如下所示
I also have the same Kotlin Class function as below
fun setPositiveButton(resId: Int, listener: DialogInterface.OnClickListener)
When I call them from a Kotlin code
javaClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
kotlinClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
可以减少Java类函数调用,但不能减少Kotlin类函数
The Java Class function call could be reduced, but not the Kotlin Class function
javaClassObj.setPositiveButton(R.string.some_string,
{ _, _ -> someFunc()})
kotlinClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
为什么Kotlin函数调用不能减少冗余SAM-Constructor按照是否已启用Java?
Why can't the Kotlin function call reduce the redundant SAM-Constructor as per enabled for Java?
推荐答案
为什么要在kotlin中使用SAM?虽然它本身支持函数。
Why would you use SAM in kotlin? while it has native support for functions.
SAM约定在java8中用作没有本机函数支持的解决方法。
The SAM convention is used in java8 as a work around not having a native function support.
:
另请注意,此功能仅适用于Java互操作;由于Kotlin
具有适当的函数类型,因此不需要将函数自动转换为
的Kotlin接口实现,因此不支持
。
Also, note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.
然后你应该直接声明一个函数。
you should then declare a function directly.
fun setPositiveButton(resId: Int, listener: (DialogInterface, Int) -> Unit) {
listener.invoke(
//DialogInterface, Int
)
}
然后可以使用
setPositiveButton(1, { _, _ -> doStuff() })
这篇关于对于Kotlin声明的函数,不能删除冗余SAM构造函数,但是对Java声明的函数起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!