Companion Object in Kotlin

Overview

If you want to write some functions or properties of a class and you want to use it without creating an instance of that class, then you should write these functions and properties in a companion object. Companion object is similar to Singleton object.

All the functions and properties in a companion object are static. 

Object vs Companion Object

Object can be used when you don't want to write some static functions or properties inside a class. Companion object can be used when you want to write some functions or properties of a class as static.

Do's and Dont's

  • You can give a name to a companion object but it's of no use. 
 class ToBeCalled {
companion object Test {
var someInteger: Int = 10
fun callMe() = println("You are calling me :)")
}
}
fun main(args: Array<String>) {
print(ToBeCalled.someInteger)
}
  • Companion object can be created outside a class.

Reference

Comments