Mastering Companion Objects in Kotlin

From Qiki
Jump to navigation Jump to search

1. What is a companion in Kotlin?

In Kotlin, you don’t have static methods or static variables like in Java. Instead, you use a companion object.

A companion object is like a special object inside a class that is shared by all instances of that class. It acts a bit like static in Java.



2. Syntax of companion object

Here’s the basic syntax:

class MyClass {
    companion object {
        val name = "Hello"
        fun greet() {
            println("Hi from companion!")
        }
    }
}

3. How to use it

You don’t need to create an object of the class. You can call it directly using the class name:

fun main() {
    println(MyClass.name)   // prints: Hello
    MyClass.greet()         // prints: Hi from companion!
}

This is very similar to calling MyClass.name or MyClass.greet() if they were static in Java.



4. Naming the companion object

You can give it a name if you want:

class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}

fun main() {
    val obj = MyClass.create()  // works fine
}

Even if you give it a name, you can still access its members with just the class name.



5. Advanced: Companion with interfaces

A companion object can also implement interfaces:

interface Logger {
    fun log(message: String)
}

class MyClass {
    companion object : Logger {
        override fun log(message: String) {
            println("Log: $message")
        }
    }
}

fun main() {
    MyClass.log("Hello")  // prints: Log: Hello
}

✅ Summary

  • companion object = Kotlin’s replacement for static.
  • Belongs to the class, not to instances.
  • You can define variables, functions, and even implement interfaces inside it.



✨ With companion objects, Kotlin gives you a clean and powerful way to handle class-level logic without static!