Companion Object in Kotlin
Introduction
Companion Object is a fundamental concept every Kotlin developer should understand. Object declarations and companion objects provide singletons, factory methods, and static-like members without the ceremony of Java static blocks.
Companion object belongs to a class and acts like static members in Java. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Companion object belongs to a class and acts like static members in Java.
- It can be accessed using class name without creating an object.
- Useful for factory methods and constants.
Syntax
companion object { fun create(): User }Companion Object in Kotlin Example Program in Kotlin
class User private constructor(val name: String) {
companion object {
fun createGuest() = User("Guest")
}
}
fun main(args: Array<String>) {
println(User.createGuest().name)
}Sample Output
GuestWhen to use
Use object for true singletons; use companion object for factory methods and constants tied to a class.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
fun createGuest() = User("Guest")assigns or updates a value used later in the program. -
The
println(User.createGuest().name)statement writes a line to the console — this produces part of the sample output below. -
Companion object belongs to a class and acts like static members in Java.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Companion object belongs to a class and acts like static members in Java.
- It can be accessed using class name without creating an object.
- Useful for factory methods and constants.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.