What if you could call class functions without making objects, keeping your code neat and fast?
Why Companion objects as static alternatives in Kotlin? - Purpose & Use Cases
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.
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.
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.
class Calculator { fun add(a: Int, b: Int): Int { return a + b } } val calc = Calculator() val result = calc.add(2, 3)
class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } val result = Calculator.add(2, 3)
You can organize utility functions inside classes and call them directly without creating objects, making your code cleaner and faster.
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.
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.