Named companion objects let you give a special name to the companion object inside a class. This helps you organize code and call its members clearly.
0
0
Named companion objects in Kotlin
Introduction
When you want to group related functions or constants inside a class.
When you want to call companion object members with a clear name to avoid confusion.
When you want to give the companion object a descriptive name like 'Factory' or 'Builder'.
When you want to improve code readability by naming the companion object.
Syntax
Kotlin
class ClassName { companion object Name { // members here } }
The keyword companion object creates a singleton object inside the class.
Giving it a name is optional but useful for clarity.
Examples
Companion object without a name. You call members as
MyClass.greet().Kotlin
class MyClass { companion object { fun greet() = "Hello" } }
Named companion object called
Factory. You call members as MyClass.Factory.create().Kotlin
class MyClass { companion object Factory { fun create() = MyClass() } }
Sample Program
This program defines a class Car with a named companion object Builder. The build function creates a new Car. In main, we call Car.Builder.build() to create a car and print it.
Kotlin
class Car { companion object Builder { fun build() = Car() } } fun main() { val myCar = Car.Builder.build() println("Car created: $myCar") }
OutputSuccess
Important Notes
The printed Car@<hashcode> is the default string representation of the object.
You can omit the name if you don't need to distinguish the companion object.
Named companion objects help clarify code and indicate the purpose of the companion object.
Summary
Named companion objects give a clear name to the singleton object inside a class.
They help organize and call companion members clearly.
Use them to improve code readability and avoid confusion.