Friday 9 February 2018

Kotlin: Scope of extension functions

If you define an extension function to a class ‘C1’, in other class ‘C2’ then the extension is visible only in ‘C2’, not from outside of ‘C2’.

class Arithmetic {
         fun sum(a: Int, b: Int): Int {
                 return a + b
         }
}

Let me define an extension function to Arithmetic class in other class ‘DemoClass1’.

class DemoClass1 {
         fun Arithmetic.sub(a: Int, b: Int): Int {
                 return a - b
         }


         fun getSubtraction(a: Int, b: Int): Int {
                 var obj = Arithmetic()
                 return obj.sub(a, b)
         }
}

when you try to access the extension function from main method, you will get an error.

fun main(args: Array<String>) {
         var obj = Arithmetic()
        
         obj.sub(10, 20)

}

Find the complete working application.

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

class DemoClass1 {
 fun Arithmetic.sub(a: Int, b: Int): Int {
  return a - b
 }


 fun getSubtraction(a: Int, b: Int): Int {
  var obj = Arithmetic()
  return obj.sub(a, b)
 }
}

fun main(args: Array<String>) {
 var obj = Arithmetic()
 
 obj.sub(10, 20)

}

When you try to compile above program, you will endup in below error.

ERROR: Unresolved reference: sub (22, 6)

Scope of top level extension functions
If you define extension functions directly under a package, then other packages can use these extension functions by importing them.

MathUtil.kt
package com.sample.util

class Arithmetic {
 fun sum(a: Int, b: Int): Int {
  return a + b
 }
}

Let me define new kotlin file ‘MathUtilExtensions’, it implements all the extension functions.


MathUtilExtensions.kt
package com.sample.util

fun Arithmetic.sub(a: Int, b: Int): Int = a - b
fun Arithmetic.mul(a: Int, b: Int): Int = a * b
fun Arithmetic.div(a: Int, b: Int): Int = a / b


As you notify above snippet, I defined three extension functions sub, mul, div to the class Arithmetic.

I can use these extension functions from other packages by importing them.

import com.sample.util.sub
import com.sample.util.mul
import com.sample.util.div


Test.kt
package com.sample.test

import com.sample.util.sub
import com.sample.util.mul
import com.sample.util.div

import com.sample.util.Arithmetic

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

 var result1 = obj.sum(10, 20)
 var result2 = obj.sub(10, 20)
 var result3 = obj.mul(10, 20)
 var result4 = obj.div(10, 20)

 println("Sum of 10 and 20 $result1")
 println("Subtraction of 10 and 20 $result2")
 println("Multiplication of 10 and 20 $result3")
 println("Division of 10 and 20 $result4")

}

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment