0
0
Kotlinprogramming~3 mins

Why Named companion objects in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how naming companion objects can turn messy static code into a neat, organized toolkit!

The Scenario

Imagine you have a class in Kotlin and you want to group some helper functions or constants inside it. Without named companion objects, you might just put everything in one unnamed companion object or use top-level functions, which can get confusing when your class grows.

The Problem

Using an unnamed companion object means all static-like members share the same space. This can make your code hard to read and maintain because you can't clearly separate different groups of helpers or constants. Also, if you want to access them, you always use the default name, which can lead to unclear code.

The Solution

Named companion objects let you create multiple companion objects inside a class, each with its own name. This helps organize your static members clearly and access them with meaningful names, making your code easier to understand and maintain.

Before vs After
Before
class MyClass {
    companion object {
        fun helper1() {}
        fun helper2() {}
    }
}
MyClass.helper1()
After
class MyClass {
    companion object Helpers {
        fun helper1() {}
    }
    // Note: Kotlin allows only one companion object per class
    // So the following companion object is invalid and should be replaced with an object declaration
    object Constants {
        const val VALUE = 42
    }
}
MyClass.Helpers.helper1()
MyClass.Constants.VALUE
What It Enables

It enables clearer organization and access to multiple groups of static members inside a single class, improving code readability and maintainability.

Real Life Example

Think of a class representing a game character. You can have one named companion object for default stats and another for utility functions like calculating damage, keeping things neat and easy to find.

Key Takeaways

Unnamed companion objects mix all static members together.

Named companion objects let you separate helpers and constants clearly.

This makes your Kotlin code cleaner and easier to work with.