Redundant SAM-constructor can't be remove for

2019-02-22 23:14发布

问题:

I have a Java Class function as below

public void setPositiveButton(int resId, DialogInterface.OnClickListener listener) 

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()})

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()})

Why can't the Kotlin function call reduce the redundant SAM-Constructor as per enabled for Java?

回答1:

Why would you use SAM in kotlin? while it has native support for functions.

The SAM convention is used in java8 as a work around not having a native function support.

from kotlin doc#sam-conversions:

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

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

and then it can be used

setPositiveButton(1, { _, _ -> doStuff() })


标签: java kotlin