extension function in a kotlin using super

前端 未结 3 1808
后悔当初
后悔当初 2021-01-18 18:06

How to call extension function of the base class in a derived class using the super keyword?

I tried to call using super but it doesn\'t work.

 open         


        
3条回答
  •  孤街浪徒
    2021-01-18 18:59

    As you created the extension out of the class it is no more member of that class. You are able to call super.aa() as it is the member of the abc class.

    In order to use that method you have to call it in following way.

    open class abc {
        open fun aa() {
            println("function in abc")
        }
    }
    fun abc.sum() {
        println("extension function")
    }
    class ab: abc() {
    
        override fun aa() {
            super.aa()
            println("functon in ab")
        }
        fun sum() {
            (this as abc).sum()
            println("sum function")
        }
    }
    fun main(args: Array < String > ) {
        var aa: ab = ab()
        aa.aa()
        aa.aa()
        aa.sum()
    }
    

    For more info refer this link

提交回复
热议问题