Redundant SAM-constructor can't be remove for Kotlin declared function, but works on Java declared function

前端 未结 2 622
渐次进展
渐次进展 2021-01-04 23:29

I have a Java Class function as below

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

I also have the s

相关标签:
2条回答
  • 2021-01-05 00:05

    Extending @humazed answer as compiler complains that

    lambda argument should be moved out of parenthesis

    setPositiveButton("ok"){_,_ -> doSomething()}
    
    0 讨论(0)
  • 2021-01-05 00:23

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

    The SAM convention is used in java8 as a workaround not having 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() })
    

    In kotlin 1.4 you can use SAM conversions for Kotlin classes.

    fun interface Listener {
        fun listen()
    }
    
    fun addListener(listener: Listener) = a.listen()
    
    fun main() {
        addListener {
            println("Hello!")
        }
    }
    
    0 讨论(0)
提交回复
热议问题