Wednesday, 7 February 2018

Kotlin: Extensions

Unlike java, you can extend the functionality of a class without creating a subclass to it. This is done by extensions. By using extensions, you can extend both the properties and methods.

How to add extension function to a type?
Prefix the function name with receiver type.

Syntax
Type.functionName(arguments) : returnType = definition

Let me explain with detailed example.

class Arithmetic {
         fun sum(a: Int, b: Int) = a + b
         fun sub(a: Int, b: Int) = a - b
}

I can add new function that multiply two numbers to the Arithmetic class using extensions like below.

fun Arithmetic.mul(a: Int, b: Int) = a * b

Find below working application.

HelloWorld.kt
class Arithmetic {
 fun sum(a: Int, b: Int) = a + b
 fun sub(a: Int, b: Int) = a - b
}

fun main(args: Array<String>) {
 fun Arithmetic.mul(a: Int, b: Int) = a * b

 var obj = Arithmetic()

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)

 println("Sum of 10 and 20 $sumOf10And20")
 println("Subtraction of 10 and 20 $subOf10And20")
 println("Multiplication of 10 and 20 $mulOf10And20")
}

Output
Sum of 10 and 20 30
Subtraction of 10 and 20 -10
Multiplication of 10 and 20 200

How to add extension property?
It is like adding extension function to a type. Remember Extension property cannot be initialized because it has no backing field, their behavior is defined only by using getter and setter methods.
Ex
         val Arithmetic.PI: Double
                 get() = 3.14

Find the below working application.


HelloWorld.kt
class Arithmetic {
 fun sum(a: Int, b: Int) = a + b
 fun sub(a: Int, b: Int) = a - b
}

class Test {
 val Arithmetic.PI: Double
  get() = 3.14

 fun getPI(): Double {
  var obj = Arithmetic()
  return obj.PI
 }
}

fun main(args: Array<String>) {
 var obj = Test()

 println("Value of PI : ${obj.getPI()}")
}


Output
Value of PI : 3.14


Previous                                                 Next                                                 Home

No comments:

Post a Comment