What is companion object in kotlin?

Published April 22, 2021

In this example we will learn what is companion object in kotlin and how to access companion object properties in kotlin.

we will called  companion object is a singleton object in kotlin, which properties are tied with the class instead of instance of the class. we can access the properties and functions directly with class name.

 

Companion object syntax

companion object {

//Body of the companion object

}

 

Point to remember about companion object

  1. Companion object properties and functions can access only by its class name not instance of the class
  2. Any class can have only one companion object
  3. Companion object can be initialized on class load time
  4. Companion object is a singleton object
  5. Companion object can has its own init block

 

A simple example on Kotlin Companion object

//Declare class
class MyCompanion{
    //class init block
    init {
        println("Init Block of Class")
    }
    //Make companion object
    companion object {
        //companion object init block
        init {
            println("Init Block of Companion object")
        }
        //property of companion object
        val name="Companion Object "

        //function in companion object
        fun printName(){
            println("Your Companion Object  name : $name")
        }
    }
}


fun main(){
    //Call method with Class name,
    //without create Instance of class,
    //like static method in java
    MyCompanion.printName()

    //access Property using class name
    val nameLen = MyCompanion.name.length

    println("MyCompanion Object Name length : $nameLen")
}

 

Output:

Init Block of Companion object
Your Companion Object  name : Companion Object
MyCompanion Object Name length : 17

 

Read how do i create a class object in kotlin

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

938 Views