Get to know Kotlin – Extension

Tram Ho

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.

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:

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”:

The above code will print the following output:

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.

Share the news now

Source : Viblo