Kotlin Extension

Kotlin Extension is an very useful feature to add and ovrload existing class methods without inherit and any pattern. that is very much effective to add new functionality to existing class. In this post we learning how to used of extension functions.

class Maths{
   fun add(x:Int=0,y:Int=0):Int{
    print("Inner add function : ")
      return x+y;
   }
}
//define extension function
//overload member functions
fun Maths.add(x:Int=0,y:Int=0 ,z:Int=0):Int{
  print("Outer add function : ")
   return x+y+z;
}
fun main(args: Array<String>){
   val obj=Maths()
   println(obj.add(1,2)) 
   println(obj.add(1,2,3))

}

Output

Inner add function : 3
Outer add function : 6

In this mechanism, defined a new member method of class at outside of class. In this case that is overload situation. But we can define other function in similar way.

Another example, suppose we are need to add new function of Int (integer) class.

//ADD new feature of Int class
fun Int.factorial():Int{
  if(this<=1) return 1
  else return ((this -1).factorial()*(this))
}

fun main(args: Array<String>){
  //work in integer value
  println("Factorial of 3 : ${3.factorial()} ")
  println("Factorial of 5 : ${5.factorial()} ")
  var num=4
  println(num.factorial()) //factorial of 4
}

Output

Factorial of 3 : 6 
Factorial of 5 : 120 
24

Note that is basic examples of Extension. This capable to add new features to inbuilt or exist user define class. In this example add new feature to integer class which are calculate factorial of number. And returns this result.

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved