Objects & Companions in Kotlin

From the Kotlin cheat sheet · Data Classes & Objects · verified Jul 2026

Objects & Companions

Singleton objects and companion objects

kotlin
// Object declaration (Singleton)
object DatabaseConnection {
    init {
        println("Initializing database connection")
    }

    fun connect() {
        println("Connecting to database...")
    }
}

// Usage
DatabaseConnection.connect()

// Companion object
class Factory {
    companion object {
        private var counter = 0

        fun create(): Factory {
            counter++
            return Factory()
        }

        fun getCount() = counter
    }
}

val instance = Factory.create()
val count = Factory.getCount()

// Named companion
class MyClass {
    companion object Loader {
        fun load() = MyClass()
    }
}
💡 object creates a singleton with thread-safe lazy initialization
⚡ Companion objects are per-class singletons for factory methods
📌 @JvmStatic makes companion methods static in Java
🟢 Object expressions create anonymous classes on the fly

Continue with Kotlin

Save the full cheat sheet or work through every related task.

More Kotlin tasks

Back to the full Kotlin cheat sheet