Kotlin - Extension

In this chapter, we can learn Kotlin - Extension.

You can add without do away with inheriting or editing them

Using extension, we will be able to add or remove some method functionality even without inheriting or modifying them.

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 approach inner "Alien" elegance named as "addMySkills()" Output

Object Extension

Using this mechanism, we will create an item of a category internal a factory technique and later we can simply name that method the use of the reference of the magnificence name. In the subsequent instance, we will create a “partner item”.

fun main(args: Array<String>) {
class A {
   companion object {
      fun show():String {
         return("You are learning Kotlin from welookups.com")
The above piece of code will yield the following output inside the browser.

Heyyy!!! You are learning Kotlin from welookups.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. You are basically extending the object of the same class to use some of the member functions