If you need a function or a property to be tied to a class rather than to instances of it (similar to static in java), you can declare it inside a companion object:
You can omit the name, in which case the name defaults to Companion,
companion object <Optional Name>{
//Companion Object Body
}
Companion objects members can only be accessed via the containing class name, not via instances of the class.
A class has only one companion object.
Companion object initializes when class is loaded, (typically when first time reference from other code).
package com.includehelp
//Declare class
class Car{
//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="Tata Altroz !! "
//function in companion object
fun printName(){
println("Your Car name : $name")
}
}
}
//Main Function, Entry Point of Program
fun main(){
//Call method with Class name,
//without create Instance of class,
//like static method in java
Car.printName()
//access Property using class name
val nameLen = Car.name.length
println("Car Name Length : $nameLen")
}
Output:
Init Block of Companion object
Your Car name : Tata Altroz !!
Car Name Length : 15
Program for companion object features in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer