Extension function in Kotlin

--

Extension provide ability for the developer to add more functionality to an existing class without inheriting it.

For example you are using a already defined class TV which have already one functionality of powerOn


class TV {
fun powerOn() {
println("Turn the Tv On")
}
}

Now you want to include one more functionality of increase volume for class TV,Now you can do this in kotlin without inheriting the class TV.

fun main() {
fun TV.volumeUp(){
println("increase the volume")
}
var tv = TV()
tv.powerOn()
tv.volumeUp()
}

If you run the above code you can see the output like below

Turn the Tv On
increase the volume

So what we did is we introduced a new functionality of volumeUp to the class TV. This is called as extension function in Kotlin

Happy Reading….. Happy Coding….

--

--

yadunath narayanan
yadunath narayanan

Written by yadunath narayanan

Passionate android developer working with android mobile and androidTv

No responses yet