Jire
Jire

Reputation: 10270

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

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
    }
}

Upvotes: 8

Views: 681

Answers (2)

osipxd
osipxd

Reputation: 1228

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
    }
}

Upvotes: 0

Varo
Varo

Reputation: 358

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.

Upvotes: 3

Related Questions