【问题标题】:Kotlin: How can I call super's extension function?Kotlin:如何调用 super 的扩展函数?
【发布时间】:2017-06-02 03:51:05
【问题描述】:

如何调用super的扩展函数?

例如:

open class Parent {
    open fun String.print() = println(this)
}

class Child : Parent() {
    override fun String.print() {
        print("child says ")
        super.print() // syntax error on this
    }
}

【问题讨论】:

    标签: kotlin extension-methods extension-function


    【解决方案1】:

    尽管print() 函数是在Parent 内部定义的,但它属于String,而不是Parent。因此,没有可以在 Parent 上调用的 print 函数,而这正是您尝试对 super 执行的操作。

    我认为您在 Kotlin 中尝试执行的调用类型没有语法支持。

    【讨论】:

      【解决方案2】:

      目前不可能,并且在 kotlin 问题跟踪器中存在问题 - KT-11488

      但您可以使用以下解决方法:

      open class Parent {
          open fun String.print() = parentPrint()
      
          // Declare separated parent print method
          protected fun String.parentPrint() = println(this)
      }
      
      class Child : Parent() {
          override fun String.print() {
              print("child says ")
              parentPrint() // <-- Call parent print here
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多