What is companion object in kotlin?
Published April 22, 2021In 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
- Companion object properties and functions can access only by its class name not instance of the class
- Any class can have only one companion object
- Companion object can be initialized on class load time
- Companion object is a singleton object
- 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 |
Read how do i create a class object in kotlin
Article Contributed By :
|
|
|
|
1280 Views |