We must use the companion keyword in front of the object definition to construct a companion object.
// Syntax in KOTLIN
class CompanionClass {
companion object CompanionObjectName {
// code
}
}
val obj = CompanionClass.CompanionObjectName
We can also remove the CompanionObject name and replace it with the term companion, resulting in the companion object\'s default name being Companion, as shown below:
// KOTLIN
class CompanionClass {
companion object {
// code
}
}
val obj = CompanionClass.Companion
All the required static member functions and member variables can be kept inside the companion object created. For example,
class Sample {
companion object Test {
var a: Int = 1
fun testFunction() = println("Companion Object’s Member function called.")
}
}
fun main(args: Array) {
println(Sample.a)
Sample.testFunction()
}
Output:-
1Companion Object’s Member function called.