Companion objects let you create functions and properties that belong to a class itself, not to its instances. They work like static members in other languages.
Companion objects as static alternatives in Kotlin
class MyClass { companion object { // static-like members here val constant = 42 fun greet() = "Hello from companion" } }
The companion object is a singleton object inside the class.
You access its members using the class name, like MyClass.greet().
class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } fun main() { println(Calculator.add(3, 4)) }
class Person { companion object { const val species = "Homo sapiens" } } fun main() { println(Person.species) }
class Logger { companion object { fun log(message: String) { println("LOG: $message") } } } fun main() { Logger.log("App started") }
This program converts Celsius to Fahrenheit using a companion object function. We call the function without creating an object.
class TemperatureConverter { companion object { fun celsiusToFahrenheit(celsius: Double): Double { return celsius * 9 / 5 + 32 } } } fun main() { val tempC = 25.0 val tempF = TemperatureConverter.celsiusToFahrenheit(tempC) println("$tempC°C is $tempF°F") }
Companion objects are initialized when the class is loaded, so their members are ready to use anytime.
You can name companion objects, but if you don't, the default name is Companion.
Companion object members can implement interfaces, which is useful for some design patterns.
Companion objects provide a way to create static-like members inside Kotlin classes.
They are useful for constants, factory methods, and utility functions related to the class.
You access companion object members using the class name without creating an instance.