Welcome to our in-depth guide on the Kotlin Companion Object! By the end of this lesson, you'll have a solid understanding of this powerful feature in Kotlin. Let's dive in!
A Companion Object is a static class associated with a primary class in Kotlin. It provides a way to share functions, objects, or constants across an instance of the class.
Think of it as a helper class for your main class, allowing you to organize related functionality in a clean and modular way.
To create a Companion Object, simply define a class and append the companion object keyword after it. Here's an example:
class Utilities {
companion object {
fun printGreeting(message: String) {
println(message)
}
}
}In this example, Utilities is the primary class, and companion object defines a helper function called printGreeting.
You can call Companion Object functions using the class name followed by dot notation:
Utilities.printGreeting("Hello, World!")Companion Objects do not have an instance, so you cannot define instance variables in them. If you need instance variables, create an instance of the companion object and define variables within that instance.
class Counter {
companion object {
private var instance: Counter? = null
fun getInstance(): Counter {
if (instance == null) {
instance = Counter()
}
return instance!!
}
var counter = 0
}
fun increment() {
counter++
}
}
val counter = Counter.getInstance()
counter.increment()
counter.increment()
println(Counter.counter) // Output: 2In this example, the Counter class has a companion object with a counter variable and a getInstance() function to ensure only one instance of the class is created.
How do you create a Companion Object in Kotlin?
We hope you've enjoyed this comprehensive guide on the Kotlin Companion Object! Stay tuned for more in-depth lessons on Kotlin and other programming topics. Happy coding! 🚀