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
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 :
|
|
|
|
938 Views |