Blog / October 26, 2020 / 2 mins read / By Suneet Agrawal

How extension functions resolved?

“how are extension functions resolved?”

This question is being asked by almost everyone both in and outside the interviews. 

Even I have asked this question to many candidates during the interview. 

The shorted or the only answer I get is “Statically”.

What does statically means?

Or how does extension functions are actually resolved?

Let’s understand this with an example.

Consider we have two classes BaseClass and DerivedClass. We added an extension function with the same function name to both the classes.

open class BaseClass

class DerivedClass : BaseClass()

fun BaseClass.someMethod(){
    print("BaseClass.someMethod")
}

fun DerivedClass.someMethod(){
    print("DerivedClass.someMethod")
}

Now if we try to call the someMethod with BaseClass reference but the actual object we passed to it will be DerivedClass object,

fun printMessage(base : BaseClass){
    base.someMethod()
}

//actual call
printMessage(DerivedClass())

This will print BaseClass.someMethod

Confused why?

Because the extension function being called depends only on the declared type of the parameter base in printMessage method, which is the BaseClass class. 

This is different from runtime polymorphism as here it is resolved statically but not at the runtime. 

It completely depends on which class object is calling the function and the extension function of that class only will be called which is why it is called static. 

The basic difference between extension functions and inheritance is references are resolved statically in extension functions whereas, in inheritance, it is resolved by run time polymorphism. If you wish to read more about the differences between inheritance and extension functions, please read this blog.

So next time if someone asks you “how are extension functions resolved?”, Please complete your answer with an example instead of just saying it is resolved statically.

Comments