This tutorial is about companion objects in Kotlin with the help of examples.
Kotlin doesn’t have a static keyword. Static members belong to a type, and not to an instance of a type.
In kotlin to achieve this static feature, we make use of companion object.
companion object
An object declaration inside a class can be marked with the companion keyword known as companion object. There can only be one companion object in a class and it is initialized when the class is loaded.
Example:
class User { companion object Test { fun show() = println("I'm inside companion object") } }
- Here, Test object declaration is marked with keyword companion to create a companion object.
Members of the companion object can be called by using simply the class name as the qualifier.
fun main() { User.show() //or User.Test.show() }
Output:
I'm inside companion object I'm inside companion object
The name of the companion object can be omitted and if the companion object name is missing, the default name Companion is assigned to it.
class User { companion object { fun show() = println("I'm inside companion object") } } fun main() { User.show() User.Companion.show() }
Similar to normal objects, companion objects cannot have constructors, but can extend other classes and implement interfaces.
Example:
companion object implementing interface Runnable.
class User {
companion object : Runnable {
override fun run() {
println("run method invoked")
}
}
}
fun main() {
User.run()
//or
User.Companion.run()
}
Output:
run method invoked run method invoked