Extensions as Members : Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/extensions-as-members-kotlin/ and reposted on Medium on 27th July 2017.
class BaseClass {
fun baseClassFunctionality() {

}
}

class OtherClass {

fun otherClassFunctionality() {

}

fun BaseClass.additionalFunctionality() {
baseClassFunctionality()
otherClassFunctionality()
}

}
class BaseClass {

fun printString() {
println("I am in BaseClass")
}
}

class OtherClass {

fun otherClassFunctionality() {
BaseClass().additionalFunctionality()
}

fun printString() {
println("I am in OtherClass")
}

fun BaseClass.additionalFunctionality() {
printString()
this@OtherClass.printString()
}

}
// the output of
OtherClass().otherClassFunctionality()
//will beI am in BaseClass
open class BaseClass {
}

class DerivedClass : BaseClass() {
}

open class OtherClass {

open fun BaseClass.someFunctionality() {
println("BaseClass.someFunctionality in OtherClass")
}

open fun DerivedClass.someFunctionality() {
println("DerivedClass.someFunctionality in OtherClass")
}

fun caller(baseClass: BaseClass) {
baseClass.someFunctionality()
}
}

class DerivedOtherClass : OtherClass() {
override open fun BaseClass.someFunctionality() {
println("BaseClass.someFunctionality in DerivedOtherClass")
}

override fun DerivedClass.someFunctionality() {
println("DerivedClass.someFunctionality in
DerivedOtherClass")
}
}
    OtherClass().caller(BaseClass())
DerivedOtherClass().caller(BaseClass())
OtherClass().caller(DerivedClass())
DerivedOtherClass().caller(DerivedClass())
  1. When we call the caller method of OtherClass with OtherClass reference object and pass the BaseClass object as the parameter.
OtherClass().caller(BaseClass())//the output of the above code will beBaseClass.someFunctionality in OtherClass
DerivedOtherClass().caller(BaseClass())//the output of the above code will beBaseClass.someFunctionality in DerivedOtherClass
OtherClass().caller(DerivedClass())//the output of the above code will beBaseClass.someFunctionality in OtherClass
DerivedOtherClass().caller(DerivedClass())//the output of the above code will beBaseClass.someFunctionality in DerivedOtherClass
  • If the extension is defined at the top level of the class, it can access all the private variables and functions of that class.
  • If the extension function is defined outside the class, it can not access the private variables or functions of that class.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store