Pass interface as parameter in Kotlin

后端 未结 2 413
刺人心
刺人心 2020-12-10 23:57

I want to pass an interface as parameter like this:

class Test {
    fun main() {
        test({})
        // how can I pass here?
    }

    fun test(handle         


        
相关标签:
2条回答
  • 2020-12-11 00:14

    In Kotlin you can do :

    test(object: Handler {
        override fun onComplete() {
    
        }
    })
    

    Or make a property the same way:

    val handler = object: Handler {
        override fun onComplete() {
    
        }
    }
    

    And, somewhere in code: test(handler)

    0 讨论(0)
  • 2020-12-11 00:40

    Attached is an example of how to pass an object by parameter that represents the value of the data type and invoke behaviors using interface inheritance.

    fun main() {
    
        val customClass = CustomClass(
                object : First {
                    override fun first() {
                        super.first()
                        println("first new impl")
                    }
                    override fun second() {
                        super.second()
                        println("second new impl")
                    }
                }
        )
    
        customClass.first.first()
        customClass.first.second()
    
    }
    
    data class CustomClass(val first: First)
    
    interface First: Second {
        fun first() {
            println("first default impl")
        }
    }
    
    
    interface Second {
        fun second() {
            println("second default impl")
        }
    }
    

    It is worth mentioning that with super.first() or super.second() the default behavior of the interface is being invoked.

    It doesn't make much sense to pass a lamda with an anonymous object as a parameter, lambda: () -> Unit , if what we need is to invoke the functions.

    GL

    Playground

    0 讨论(0)
提交回复
热议问题