使用super在kotlin中扩展功能 [英] extension function in a kotlin using super

查看:147
本文介绍了使用super在kotlin中扩展功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用super关键字在派生类中调用基类的扩展功能?

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

我尝试使用super打电话,但是它不起作用.

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

 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() {
         super.sum()
         println("sum function")
     }
 }
 fun main(args: Array < String > ) {
     var aa: ab = ab()
     aa.aa()
     aa.aa()
     aa.sum()
 }

这里是第16个数字行错误,我不能调用扩展功能.

Here is the 16th number line error comes, I can't call the extension function.

推荐答案

在类之外创建扩展时,该类不再是该成员.您可以调用super.aa(),因为它是abc类的成员.

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

这篇关于使用super在kotlin中扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆