Thursday 8 February 2018

Kotlin: Extensions to companion object

In my previous post, I explained how to set extensions to an existing class. In this post, I am going to explain how to set extensions to companion object.

Syntax
fun Type.Companion.functionName(arguments) = definition

C is capital in ‘Companion’

Ex
         fun TestClass.Companion.sum(a: Int, b: Int): Int {
                 return a + b
         }

Just like the normal companion functions call, you can call extension functions.

TestClass.sum(10, 20)

Find the below working application.

HelloWorld.kt
class TestClass {
 companion object {
  fun sayHello() {
   println("Hello")
  }
 }
}

fun main(args: Array<String>) {
 fun TestClass.Companion.sum(a: Int, b: Int): Int {
  return a + b
 }

 var sumOfNumbers = TestClass.sum(10, 20)

 println("Sum of 10 and 20 $sumOfNumbers")
}

Output
Sum of 10 and 20 30



Previous                                                 Next                                                 Home

No comments:

Post a Comment