Hello friends, today we will learn about another new feature of Kotlin called “Extension”. Using the extension, we will be able to add or remove some method functions even without inheriting or modifying them. Extensions are resolved by static. It doesn’t actually modify the existing class, but it creates a callable function using a period before the function name.
Function Extension
In function extension, Kotlin allows defining a method outside the main class. In the following example, we will see how the extension is implemented at the function level.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Alien{ var skills : String= "null" fun printMySkills(){ print(skills) } } fun main(args: Array<String>) { var a1= Alien() a1.skills="JAVA" //a1.printMySkills() var a2= Alien() a2.skills="SQL" //a2.printMySkills() var a3= Alien() a3.skills=a1.addMySkills(a2) a3.printMySkills() } fun Alien.addMySkills(a:Alien):String{ var a4=Alien() a4.skills=this.skills + " " +a.skills return a4.skills } |
In the above example we don’t have any method inside the “Alien” class named addMySkills () , however we are implementing the same method somewhere else outside this class, this is what magic of the extension.
The above code will print the following output:
1 2 | JAVA SQL |
Object Extension
Kotlin provides another mechanism for implementing Java static functions. This can be achieved by using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a root method, and we can call that method later using the class name’s reference. In the following example, we will create a “companion object”:
1 2 3 4 5 6 7 8 9 10 11 | fun main(args: Array<String>) { println("Heyyy!!!"+A.show()) } class A{ companion object{ fun show():String{ return("You are learning Kotlin from viblo.asia") } } } |
The above code will print the following output:
1 2 | Heyyy!!! You are learning Kotlin from viblo.asia |
The above example looks like static in Java, however, in real-time we are creating an object as a member variable of the same class. This is why it is also included in the extension property and can be called otherwise object extension. Basically, you are extending the object of the same class to use some member functions.
I would like to stop writing here, the article includes a little theory and illustrative examples, hope this will be useful. Thank you.