Showing posts with label companion object. Show all posts
Showing posts with label companion object. Show all posts

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

Friday, 19 January 2018

Kotlin: Companion Objects

By using companion object, you can access the members using the class name (no need to define the object).

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

fun main(args: Array<String>) {
 TestClass.sayHello()
}

Output
Hello

As you see above code snippet, I called sayHello function of companion object using TestClass (not created any object to TestClass).

You can give name to companion object.

         companion object FunModules {
                 fun sayHello() {
                          println("Hello")
                 }
         }


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

fun main(args: Array<String>) {
 TestClass.sayHello()
}

Output
Hello


By adding @JvmStatic annotation on top of companion object, you can use it as static member in any java class.


HelloWorld.kt
import kotlin.jvm.JvmStatic

class TestClass {
 companion object {
  @JvmStatic
  fun sayHello() {
   println("Hello")
  }
 }
}

CompanionDemo.java

public class CompanionDemo {
 public static void main(String args[]){
  TestClass.sayHello();
 }
}


Output

Hello


Previous                                                 Next                                                 Home