— Kotlin, Companion Objects — 1 min read
A companion object is an object that belongs to a class and is defined inside the same file as the class itself. It is similar to Java's static methods and properties but is more powerful since it can also implement interfaces and extend classes. A companion object is created using the companion
keyword followed by the object definition.
1class MyClass {2 companion object {3 // Properties and methods go here4 }5}
One important thing to note is that a companion object is a singleton, which means that there is only one instance of it per class. This can be useful when you want to create global access to a set of related functions or properties.
There are several ways to use companion objects in Kotlin. One common use case is to define factory methods. For example, suppose you have a class called Person
and you want to provide a way to create instances of the class with default values for certain properties. You can use a companion object to define a factory method that returns an instance of Person
with the desired default values.
1class Person(val name: String, val age: Int) {2 companion object {3 fun createDefault(): Person {4 return Person("John Doe", 18)5 }6 }7}8
9// Usage10val person = Person.createDefault()11println(person.name) // Output: John Doe12println(person.age) // Output: 18
Another use case for companion objects is to define constants or shared properties. In the following example, we define a constant PI
inside a companion object that belongs to the Circle
class.
1class Circle(val radius: Double) {2 companion object {3 const val PI = 3.141594 }5 6 fun area(): Double {7 return PI * radius * radius8 }9}10
11// Usage12val circle = Circle(5.0)13println(circle.area()) // Output: 78.53975
You can also use companion objects to implement interfaces or extend classes. In the following example, we define a companion object that extends the Comparator
interface to compare two instances of Person
based on their ages.
1class Person(val name: String, val age: Int) {2 companion object AgeComparator : Comparator<Person> {3 override fun compare(p1: Person, p2: Person): Int {4 return p1.age - p2.age5 }6 }7}8
9// Usage10val people = listOf(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20))11println(people.sortedWith(Person.AgeComparator)) // Output: [Charlie, Alice, Bob]
Companion objects are a powerful feature in Kotlin that can help you write more concise and readable code. They allow you to define functions, properties, constants, and even implement interfaces or extend classes that are related to a specific class. By using companion objects, you can create global access to these related elements without polluting the global namespace.