How extension functions resolved?

Suneet Agrawal
2 min readDec 15, 2019

--

“how 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”.

This post was originally posted at https://agrawalsuneet.github.io/blogs/inheritance-vs-extension-functions/ and reposted on Medium on 16th Dec 2019.

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?

Please continue reading at https://agrawalsuneet.github.io/blogs/how-extension-functions-resolved/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

No responses yet