Skip to main content
Browse topics

Companion Object in Kotlin

2 min read Updated June 30, 2026
Share

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

kotlin
companion object { fun create(): User }

Companion Object in Kotlin Example Program in Kotlin

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

plaintext
Guest

When to use

Use object for true singletons; use companion object for factory methods and constants tied to a class.

How it works

  1. The program starts with a main function — the entry point that runs when you execute the file.

  2. fun createGuest() = User("Guest") assigns or updates a value used later in the program.

  3. The println(User.createGuest().name) statement writes a line to the console — this produces part of the sample output below.

  4. Companion object belongs to a class and acts like static members in Java.

  5. 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.

Frequently Asked Questions

What is Companion Object in Kotlin?
Companion object belongs to a class and acts like static members in Java.
When should I use Companion Object?
Use object for true singletons; use companion object for factory methods and constants tied to a class.
How is Companion Object different from Java?
Useful for factory methods and constants.
How do I practice this topic?
Copy the example program into IntelliJ IDEA or Android Studio, run it, then modify values or add print statements to confirm your understanding.

Related tutorials

Search tutorials