chirag contractor
chirag contractor

Reputation: 19

Is extension function member function of particular class?

Here two classes are given class A & B. class A has a extension function as a sub() and derived class B also has a same name function sub().If the extension function is member function of class A then why it can not be access by super keyword ????

open class A(var s : Int){
    var a : Int = 5
    var b : Int = 4
    var c : Int = 0
    constructor() : this(7) {
        //println("class A constructor has been called !!!")
        println("primary constructor value is $s")
    }
   fun add(h:Int) {
        c = a.plus(b)
        println("h is for class A $h")
    }
    fun dis(){
        println("sum of a & b is $c")

    }
}
fun A.sub(){

    println("sub of class A is ${a.minus(b)}")

}
class B: A{

    constructor(){
        println("primary constructor for class B")

    }
    fun sub(){
        super.sub();
        println("sub of class B is ${a.minus(b)}")

    } 

}
fun main(args:Array<String>){
    var b = B()
    b.add(2)
    b.dis()
    b.sub()
}

Upvotes: 1

Views: 68

Answers (2)

hardik gosai
hardik gosai

Reputation: 398

Extension function is a member function , but i don't know wht we can't call it using super keyword, but we have it's alternative way to call it like super.. So modified your code as shown below..

fun A.sub(){
    println("sub of class A is ${a.minus(b)}")
}
class B: A{
    constructor(){
        println("primary constructor for class B")
    }
    fun sub(){ 
         (this as A).sub()
         println("sub of class B is ${a.minus(b)}")
    } 
}

Upvotes: 1

Pawel
Pawel

Reputation: 17248

Extension functions are not members of the class. They are essentially static methods that conveniently appear as a member when typing them in Kotlin.

You are not able to access any private members of receiver object:

class MyClass(private val b : Int) { }

fun MyClass.extFun() = b // Cannot access 'b': it is private in 'MyClass'

When calling it from Java the syntax is following:

MyClassKt.extFun(myClass);  // if extension is in file MyClass.kt

Upvotes: 1

Related Questions