Companion object in Kotlin

Companion object in Kotlin

Overview:

Unlike Java, Kotlin does not have static members or member functions. If you want to access the members or member functions without instantiating class, use the companion object declaration

Example: How to use a companion object

class Sample {
      fun getData() {
          print("Data")
      }
}
fun main(args: Array<String>) {
      val obj = Sample()
      obj.getData()
}

In above code, we have to create the object to access the member function. Using companion object, we dont need to create the object, directly you can access members using class name. See below code

class Sample {
      companion object {
            fun getData() {
                print("Data")
            } 
      }
}
fun main(args: Array<String>) {
      Sample.getData()
}

How to Call Companion Object from Java code:

We can call Kotlin function from Java code using below options.

//Kotlin class
class Sample {
      companion object {
            @JvmStatic
            fun getData() : String {
                return "Data"
            } 
      }
}

// Java Class
class UtilClass {
      void printData() {
          //need to use "Companion" to access kotlin function from java code with out creating Kotlin class object
          String data = Sample.Companion.getData(); 
          //One more way is, you can use @JvmStatic keyword in kotlin function if you want to access kotlin function like noremal static java class
          String value = Sample.getData();
      }

}