10

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

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

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
hardik gosai
  • 328
  • 3
  • 17

3 Answers3

12

This will do:

(this as abc).sum()

super does not work as extension functions are not members of the base class to be overridden in derived classes.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
5

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

Brijesh Joshi
  • 1,817
  • 1
  • 9
  • 24
3

This type of namespace conflict is a general drawback of extension methods. Extension methods are essentially static and do not mix well with inheritance.

In your particular case, there doesn't seem to be a need for the function sum to be an extension method. If you change it to an open virtual method, you will be able to design better for inheritance and potential overriding in a subclass.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
  • Now see my code fun sum() { super.sum() println("sum function") } here aa() and sum() both are member function , we can call aa() using super then why we can't call the sum() ? – hardik gosai Jul 04 '18 at 09:54