lambda expression on interface in Kotlin

前端 未结 2 1784
一向
一向 2020-12-19 08:15

I\'m converting a project in Java to Kotlin and I\'m surprise that interface made the code heavier in Kotlin than in Java.

Example: I want to set t

相关标签:
2条回答
  • 2020-12-19 08:45

    The lambda version works only when kotlin interop with java because SAM Conversions, see the official documents.

    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.

    So if you want use lambda to set the listener with pure kotlin, you can define your listener and setOnBackPressed method like this:

    var listener: (() -> Unit)? = null
    
    fun setOnBackPressed(l: () -> Unit) {
        listener = l
    }
    

    then invoke it by:

    listener?.invoke()
    
    0 讨论(0)
  • 2020-12-19 09:05

    You use Java style while use Kotlin =)

    If you really want to use OnBackPressedListener you can just wrap it in inline function, like:

    inline fun backPress(crossinline action:()->Unit):OnBackPressedListener {
        return object: OnBackPressedListener {
            override fun onBackPressed() {
                action()
            }
        }
    }
    

    And then just set listener

    activity.setOnBackPressed(backPress {  
    /* Do something */
    })
    
    0 讨论(0)
提交回复
热议问题