0
0
Kotlinprogramming~3 mins

Why Companion objects as static alternatives in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could call class functions without making objects, keeping your code neat and fast?

The Scenario

Imagine you want to create a utility function in Kotlin that belongs to a class but doesn't need an instance to work, like a calculator's add method. Without companion objects, you'd have to create an object every time or place the function outside the class, which feels disconnected.

The Problem

Manually creating instances just to call utility functions wastes memory and time. Placing functions outside classes breaks the idea of grouping related code, making your program messy and harder to understand.

The Solution

Companion objects let you put functions and properties inside a class that behave like static members. This means you can call them without creating an instance, keeping your code organized and efficient.

Before vs After
Before
class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
}
val calc = Calculator()
val result = calc.add(2, 3)
After
class Calculator {
    companion object {
        fun add(a: Int, b: Int) = a + b
    }
}
val result = Calculator.add(2, 3)
What It Enables

You can organize utility functions inside classes and call them directly without creating objects, making your code cleaner and faster.

Real Life Example

Think of a Logger class where you want to log messages without creating a Logger instance every time. Companion objects let you call Logger.log("message") directly.

Key Takeaways

Companion objects provide a way to create static-like members inside classes.

They help avoid unnecessary object creation for utility functions.

They keep related code grouped and easy to find.