Kotlin: How can I call super's extension function?
Asked Answered
A

2

8

How can I call a super's extension function?

For example:

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
    }
}
Aemia answered 2/6, 2017 at 3:51 Comment(0)
C
3

Even though the print() function is defined inside of Parent, it belongs to String, not to Parent. So there's no print function that you can call on Parent, which is what you're trying to do with super.

I don't think there's syntax support for the type of call you're trying to do in Kotlin.

Contumacy answered 2/6, 2017 at 16:6 Comment(0)
A
0

It is not possible for now, and there is an issue in the kotlin issue-tracker - KT-11488

But you can use the following workaround:

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
    }
}
Abrahan answered 3/5, 2021 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.