WEB Button DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Kotlin - Extension


In this chapter, we will learn Kotlin - Extension.

You can add without remove inheriting or modifying them

Function Extension

Kotlin allows to define a method outside of the main class

Let's see following example how the extension is implemented at the functional level.

class Alien {
   var skills : String = "null"
	
   fun printMySkills() {
      print(skills)
   }		
}
fun main(args: Array) {
   var  a1 = Alien()
   a1.skills = "Play"
   //a1.printMySkills()
	
   var  a2 = Alien()
   a2.skills = "Read"
   //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 “Alien” class named as "addMySkills()" Output
Play Read

Object Extension

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) {
   println("Hello!!!"+A.show())
}
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 in the browser.

You are learning Kotlin from Welookups.com