Kotlin - Extension


In this chapter, we will learn about another new feature of Kotlin named “Extension”. Using extension, we will be able to add or remove some method functionality even without inheriting or modifying them. Extensions are resolved statistically. It does not actually modify the existing class, but it creates a callable function that can be called with a dot operation.

Function Extension

In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level.

class Alien {
   var skills : String = "null"
   fun printMySkills() {
fun main(args: Array<String>) {
   var  a1 = Alien()
   a1.skills = "JAVA"
   var  a2 = Alien()
   a2.skills = "SQL"
   var  a3 = Alien()
   a3.skills = a1.addMySkills(a2)
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 “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension.

The above piece of code will generate the following output in the browser.


Object Extension

Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”.

fun main(args: Array<String>) {
class A {
   companion object {
      fun show():String {
         return("You are learning Kotlin from TutorialsPoint.com")

The above piece of code will yield the following output in the browser.

Heyyy!!! You are learning Kotlin from TutorialsPoint.com

The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions.

Useful Video Courses


Kotlin Online Training

68 Lectures 4.5 hours

Arnab Chakraborty


Kotlin Masterclass Programming: Android Coding Bible


71 Lectures 5.5 hours

Frahaan Hussain


Android Dependency Injection using Dagger with Kotlin

18 Lectures 1.5 hours

Mahmoud Ramadan


Android Retrofit complete course in Kotlin

49 Lectures 6 hours

Catalin Stefan


Master Kotlin - Learn Kotlin to develop android apps

49 Lectures 2.5 hours



Breeze Music Player - Learn Kotlin, MVVM and MediaPlayer API

22 Lectures 1 hours