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

No comments:

Post a Comment