0
0
Kotlinprogramming~5 mins

Companion objects as static alternatives in Kotlin

Choose your learning style9 modes available
Introduction

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.

When you want to group helper functions related to a class but not tied to any object.
When you need to create factory methods to build instances in a special way.
When you want to hold constants inside a class for easy access.
When you want to access class-level properties or methods without creating an object.
Syntax
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().

Examples
Defines a companion object with a static-like add function. Called using the class name.
Kotlin
class Calculator {
    companion object {
        fun add(a: Int, b: Int) = a + b
    }
}

fun main() {
    println(Calculator.add(3, 4))
}
Stores a constant inside the companion object, accessed via the class.
Kotlin
class Person {
    companion object {
        const val species = "Homo sapiens"
    }
}

fun main() {
    println(Person.species)
}
Uses companion object to create a static-like log function.
Kotlin
class Logger {
    companion object {
        fun log(message: String) {
            println("LOG: $message")
        }
    }
}

fun main() {
    Logger.log("App started")
}
Sample Program

This program converts Celsius to Fahrenheit using a companion object function. We call the function without creating an object.

Kotlin
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")
}
OutputSuccess
Important Notes

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.

Summary

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.