对于Kotlin声明的函数,不能删除冗余SAM构造函数,但是对Java声明的函数起作用 [英] Redundant SAM-constructor can't be remove for Kotlin declared function, but works on Java declared function

查看:655
本文介绍了对于Kotlin声明的函数,不能删除冗余SAM构造函数,但是对Java声明的函数起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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)



<当我从Kotlin代码中调用它们时

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.


请注意,SAM转换仅适用于接口,而不适用于抽象
类,即使这些类也只有一个摘要方法。

Note that SAM conversions only work for interfaces, not for abstract classes, even if those also have just a single abstract method.

另请注意,此功能仅适用于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声明的函数起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆