TExcelTAD
Home › Kotlin › Kotlin Objects & Companion Objects

Kotlin Objects and Companion Objects

Kotlin's object keyword creates a class and its single instance at the same time. It replaces three things Java needs separate tools for: singletons, static members and anonymous classes.

Form Purpose
object Name { … } object declaration — a singleton
companion object { … } members that belong to the class, not to instances (like Java static)
object : Interface { … } object expression — an anonymous one-off object

Object declarations (singletons)

kotlin · try it yourself
object AppConfig {
    val appName = "TaskBoard"
    var darkMode = false

    fun summary() = "$appName (dark mode: $darkMode)"
}

fun main() {
    println(AppConfig.summary())
    AppConfig.darkMode = true
    println(AppConfig.summary())
}
TaskBoard (dark mode: false)
TaskBoard (dark mode: true)

There is exactly one AppConfig, created lazily the first time it's used, and it's thread-safe. You access it by its name — no constructor call.

Objects can extend classes and implement interfaces:

kotlin · try it yourself
interface Logger { fun log(msg: String) }

object ConsoleLogger : Logger {
    private var count = 0
    override fun log(msg: String) {
        count++
        println("[$count] $msg")
    }
}

fun process(logger: Logger) {
    logger.log("start")
    logger.log("done")
}

fun main() {
    process(ConsoleLogger)
    ConsoleLogger.log("again")
}
[1] start
[2] done
[3] again

Companion objects

Kotlin classes have no static keyword. Members that belong to the class as a whole go into a companion object and are called on the class name. A typical use is a factory function next to a private constructor:

kotlin · try it yourself
class User private constructor(val name: String, val isGuest: Boolean) {
    companion object {
        private var guestCounter = 0
        const val MAX_NAME = 20

        fun registered(name: String) = User(name.take(MAX_NAME), false)
        fun guest(): User {
            guestCounter++
            return User("guest$guestCounter", true)
        }
    }

    override fun toString() = if (isGuest) "$name (guest)" else name
}

fun main() {
    println(User.registered("Amira"))
    println(User.guest())
    println(User.guest())
    println(User.MAX_NAME)
}
Amira
guest1 (guest)
guest2 (guest)
20

Because the constructor is private, User("x", true) can't be called from outside — all users are created through the factories.

Object expressions

An object expression creates an anonymous object on the spot — useful for a one-off implementation of an interface or an ad-hoc bundle of values:

kotlin · try it yourself
interface Greeter { fun greet(name: String): String }

fun main() {
    val pirate = object : Greeter {
        override fun greet(name: String) = "Ahoy, $name!"
    }
    println(pirate.greet("Jack"))

    val point = object {
        val x = 3
        val y = 4
    }
    println(point.x + point.y)
}
Ahoy, Jack!
7

data object

A data object is a singleton with a generated readable toString() — useful in sealed hierarchies:

kotlin · try it yourself
object Plain
data object Pretty

fun main() {
    println(Pretty)
    println(Plain.toString().startsWith("Plain@"))
}
Pretty
true

Choosing

You want… Use
exactly one shared instance (registry, config, logger) object
a factory function or constant tied to a class companion object
a quick implementation used in one place object : expression (or a lambda for fun interfaces)

Note: Singletons are global state. They are fine for constants and stateless helpers, but for things you want to replace in tests (like a database), prefer passing an interface as a parameter.

Test yourself

How many instances of object Registry { } exist?

  1. One per call
  2. Exactly one
  3. Zero until you call Registry()
  4. As many as you create

What replaces Java's static members in a Kotlin class?

  1. static keyword
  2. A companion object
  3. An init block
  4. A top-level val only

What does object : Runnable { override fun run() { } } create?

  1. A singleton named Runnable
  2. An anonymous object implementing Runnable
  3. A new interface
  4. A compile error