In Kotlin, companion objects are used to create static functions and properties, just like the ones we create in Java and C# using the static
keyword. We don’t need to create a class object to call these functions and properties. Instead, these properties and functions can be called directly by using the dot operator on the class name. One class can have only one companion object at a time.
There are multiple ways to declare a companion object.
Without a name: Companion objects can be declared without a name, and by default, their name is companion
:
class Cat {companion object {fun makeSound() = println("Mew mew")}}fun main() {Cat.makeSound()}
The explanation of the code is given below:
Line 1: We are declaring a class called Cat
.
Line 2: Within the Cat
class, we are declaring a companion object.
Line 3: Within the companion object, we declare a function named makeSound()
that prints "Mew mew" to the console. The =
indicates that this is a single-expression function where the result of the expression is returned automatically.
Lines 6–7: We declare the main()
function, which serves as the entry point of the program, and call the makeSound()
function defined within the companion object of the Cat
class. This line will print "Mew mew" to the console when executed.
With a name: Companion objects can also be declared with a name, which helps make the code clearer, readable, and maintainable.
class Cat {companion object Kitty {fun makeSound() = println("Mew Mew")}}fun main() {Cat.Kitty.makeSound()//Can also be done asCat.makeSound()}
The explanation of the code is given below:
Line 2: Within the Cat
class, we are declaring a companion object with the name Kitty
that will perform the same functionality of printing "Mew Mew" on the console.
Line 7: In the main()
function, which serves as the entry point of the program, we call the makeSound()
function with the name of the companion object of the Cat
class. This line will print "Mew mew" to the console when executed.
Companion objects can also be used to implement the
class Cat {companion object {fun createObject() = Cat()}}fun main() {// Usageval cat: Cat = Cat.createObject()println("Cat: $cat")}
Let's see the explanation of the code:
Line 1–2: We are declaring a class named Cat
and within the Cat
class, we declare a companion object.
Line 3: Within the companion object, we declare a function named createObject()
that returns a new instance of the Cat
class. When createObject()
is called, it creates and returns a new Cat
object.
Lines 6–8: We declare the main()
function, which serves as the entry point of the program, and create a new variable named cat
type Cat
. It assigns the result of calling the createObject()
function from the companion object of the Cat
class to this variable. In other words, it creates a new instance of the Cat
class using the factory method createObject()
.
Line 9: We print the string "Cat: "
followed by the value of the cat
variable. In Kotlin, the $
symbol is used for string interpolation, allowing you to embed expressions directly within strings. In this case, it prints the value of the cat
variable, which is the newly created Cat
object.
Companion objects can be used to declare properties and functions that are common with all members of the class. For example, all cats make the sound of mew and all cats have the species "Felis catus."
class Cat {companion object {fun makeSound() = println("Mew Mew")val species = "Felis catus"}}fun main() {Cat.makeSound()println(Cat.species)}
Let's see the explanation of the code:
Line 1–2: We are declaring a class named Cat
and within the Cat
class, we declare a companion object.
Lines 3: Within the companion object, we declare a function named makeSound()
that prints "Mew Mew" to the console when called.
Line 4: Within the companion object, we declare a read-only property named species
with the value "Felis catus". This property holds the species of the cat, and it's common to all instances of the Cat
class.
Lines 7–8: We declare the main()
function, which serves as the entry point of the program, and call the makeSound()
function defined within the companion object of the Cat
class. It prints "Mew Mew" to the console.
Line 9: We print the value of the species
property from the companion object of the Cat
class. It prints "Felis catus" to the console.
Note: Companion objects are loaded the first time the class containing it is loaded. Thus, we should avoid over use of companion objects.
In conclusion, companion objects in Kotlin serve the purpose of providing a mechanism to define properties and functions that are tied to a class itself rather than to instances of the class. They allow for the organization of shared functionality and constants within a class, promoting encapsulation and code organization. Companion objects offer a convenient way to implement factory methods, define static members, and centralize common functionality, contributing to cleaner and more maintainable code in Kotlin projects.
Unlock your potential: Kotlin series, all in one place!
To continue your exploration of Kotline, check out our series of Answers below:
How to use companion objects in Kotlin
Learn how Kotlin's companion objects enable calling class members without creating an instance, similar to static methods in Java.
How to create a singleton class in Kotlin
Learn how to implement the singleton pattern in Kotlin using the object
declaration for single-instance access to resources.
What are sealed classes in Kotlin?
Learn how sealed classes in Kotlin restrict inheritance to a predefined set, enhancing control and type safety in coding.
What is the purpose of Companion Object in Kotlin?
Learn how Kotlin's companion objects create static properties and functions, centralize shared attributes, and implement factory methods for cleaner, maintainable code.
Data types in Kotlin
Learn how Kotlin categorizes data types into primitive and reference types, supporting numbers, characters, booleans, arrays, strings, classes, functions, and nullable types.
Descending sort of 0s, 1s, and 2s in kotlin
Learn how to modify the Dutch National Flag algorithm in Kotlin to efficiently sort arrays of 0s, 1s, and 2s in descending order with O(N) time and O(1) space complexity.
Free Resources