object, companion object and Singletons

object, companion object and Singletons in Kotlin: At the centre of a working shipyard hangs a single tide board: one chalked panel, visible from every dock,…

The Analogy: The Shipyard Tide Board and the Harbour-Master's Desk

At the centre of a working shipyard hangs a single tide board: one chalked panel, visible from every dock, showing the current height of the water. There is exactly one of it in the whole yard. No crew builds their own; they all walk to the same board, read the same figure, and when the tideman updates it, the new reading is instantly the truth for everyone. The board is not chalked up the moment the yard is built, either -- it sits blank until the first crew actually needs a reading, and only then is it filled in. This is the Kotlin object declaration: a singleton created lazily on first access, with one shared instance that the whole program reads and writes.

Off to the side of each dock stands a harbour-master's desk, and this is a different kind of fixture. The desk belongs to a particular dock -- Dock 3's desk is not a separate dock, it is the counter attached to that dock's operation. A skipper can walk up to Dock 3's harbour-master and be issued a berth permit without any ship yet being present, because the desk exists independently of the vessels that use it. The desk also keeps a running tally of how many permits it has issued for that dock. A Kotlin companion object is this desk: a single object tied to a class by name, reached through the class itself rather than through any instance, and the natural home for factory functions that hand out fresh instances and for counters that span the whole class.

There is a third, lighter fixture too. For a one-off regatta, the yard wheels out a plain chalkboard easel, scribbles the day's start times on it, uses it for the afternoon, and rolls it away. It has no name painted on it and no permanent place; it exists only for the moment it is needed. This is an object expression -- an anonymous object created inline, often to satisfy an interface for a single call site, discarded as soon as its purpose is served. It gives you the shape of an object without the ceremony of a named declaration.

The failure that fouls the yard is the clerk who starts writing a single ship's private manifest onto the shared tide board because it is convenient and always in view. Now every crew sees one vessel's cargo list, and worse, the next clerk chalks a different ship's manifest over the top of it. The board was meant to hold one shared fact; loading it with per-request data turns a shared reference into a collision point. In Kotlin this is the trap of stuffing mutable, request-specific state into a singleton object: because there is only ever one instance, every caller shares and overwrites it, and in a concurrent program that shared mutable state is a race waiting to happen.


Syntax or Core Structure

An object declaration defines a singleton: the type and its single instance in one stroke, initialised lazily on first access. A companion object is a singleton tied to a class, whose members are reached through the class name.

object TideBoard {
    var heightCm: Int = 0
    fun read(): String = "tide " + heightCm + "cm"
}

class Berth private constructor(val id: Int) {
    companion object {
        private var issued = 0
        fun open(id: Int): Berth {
            issued += 1
            return Berth(id)
        }
        fun count(): Int = issued
    }
}

fun main() {
    TideBoard.heightCm = 210
    println(TideBoard.read())
    val b = Berth.open(3)
    Berth.open(4)
    println("berth " + b.id + ", opened " + Berth.count())
}

Output:

tide 210cm
berth 3, opened 2

TideBoard is a singleton: TideBoard.heightCm = 210 writes to the one and only instance, and read() reports it. Berth hides its constructor with private constructor and exposes a companion object factory open, so callers say Berth.open(3) rather than Berth(3). The companion keeps a class-wide issued counter; two calls to open raise it to 2, which Berth.count() reports. Members of the companion are reached through the class name itself, giving Kotlin the ergonomics of static members without a static keyword.


Technical Depth: Kinds of object, Naming, and Laziness

The three forms compared

The keyword object appears in three roles, and it helps to hold them apart.

FormInstancesReached byTypical use
object Name { } (declaration)exactly oneName.membersingleton, shared state
companion object { }one per classClassName.memberfactories, class constants
object : Iface { } (expression)one, anonymousthe value it returnsad-hoc interface impl
regular classmany, via constructorinstance referencesordinary modelled data

An object declaration and a companion object are both singletons; the difference is that the companion is addressed through its enclosing class, while a standalone object is addressed through its own name.

A companion object can be named and can implement an interface

A companion is a real object, so it can carry a name and satisfy an interface -- which is how Kotlin models things like a factory that must conform to a contract.

interface Factory<T> {
    fun make(seed: Int): T
}

class Token(val value: Int) {
    companion object Mint : Factory<Token> {
        override fun make(seed: Int): Token = Token(seed * 10)
    }
}

fun main() {
    val viaClass = Token.make(3)
    val viaName = Token.Mint.make(4)
    println(viaClass.value)
    println(viaName.value)
}

Output:

30
40

The companion is named Mint and implements Factory<Token>. You can call it through the class (Token.make(3)) or through its explicit name (Token.Mint.make(4)); both reach the same single companion instance. With seeds 3 and 4, make returns tokens of value 30 and 40. Because the companion satisfies Factory<Token>, it can be passed anywhere a Factory<Token> is expected -- a genuine object, not a bag of statics.

An object expression captures its enclosing scope

An anonymous object created inline can implement an interface on the spot and can read variables from the enclosing function.

interface Sink {
    fun accept(n: Int)
    fun total(): Int
}

fun collectInto(values: List<Int>): Int {
    var sum = 0
    val sink = object : Sink {
        override fun accept(n: Int) { sum += n }
        override fun total(): Int = sum
    }
    values.forEach { sink.accept(it) }
    return sink.total()
}

fun main() {
    println(collectInto(listOf(4, 5, 6)))
}

Output:

15

The anonymous object implements Sink for this one call and closes over the local sum, mutating it as each value arrives. Summing 4, 5, and 6 gives 15. Unlike an object declaration, an object expression is not a singleton -- a fresh one is built every time collectInto runs -- and it can reach the local state around it, which a named declaration cannot.

A declaration initialises lazily, on first touch

An object declaration does not run its initializer at program start. It is constructed the first time any of its members is accessed, and exactly once thereafter.

object Ledger {
    init { println("ledger initialised") }
    var entries: Int = 0
}

fun main() {
    println("before touch")
    Ledger.entries = 5
    Ledger.entries += 1
    println("entries " + Ledger.entries)
}

Output:

before touch
ledger initialised
entries 6

"before touch" prints while Ledger is still uninitialised -- merely mentioning the type in source does not construct it. The first actual access, Ledger.entries = 5, triggers the init block, so "ledger initialised" appears at that point and only that point; the second access does not re-run it. The counter ends at 6 after the assignment and increment. This laziness is why side effects in an object initializer fire at an unpredictable moment rather than at startup.

One companion, but many named nested objects

A class may have only a single companion object, reached through the bare class name. When you want more than one grouped namespace on a class, add named nested objects alongside the companion.

class Palette {
    companion object {
        val primary: String = "blue"
    }
    object Dark {
        val primary: String = "navy"
    }
}

fun main() {
    println(Palette.primary)
    println(Palette.Dark.primary)
}

Output:

blue
navy

Palette.primary reaches the companion member directly, because companion members are addressed through the enclosing class with no extra qualifier. Palette.Dark.primary reaches a distinct named nested object, which is a separate singleton grouped under the class. A second companion object would not compile, so named nested objects are the way to attach additional shared namespaces to one class.


Real World Example: A Shared ID Generator

An order-processing job assigns each order a sequence number. The team reaches for the obvious tool -- a singleton IdGenerator object -- and has every Order pull its id from it at construction. The intent is that each batch of orders numbers its items starting from 1, so a batch can be printed as "orders 1 and 2" regardless of what other batches ran that day.

object IdGenerator {
    private var next = 1
    fun nextId(): Int = next++
}

class Order(val label: String) {
    val id: Int = IdGenerator.nextId()
}

fun processBatch(items: List<String>): List<Int> =
    items.map { Order(it).id }        // intended: each batch numbers from 1

fun main() {
    val morning = processBatch(listOf("a", "b"))
    val evening = processBatch(listOf("c", "d"))
    println("morning ids: " + morning)
    println("evening ids: " + evening)
}

Output:

morning ids: [1, 2]
evening ids: [3, 4]

The morning batch behaves as hoped: two orders take ids 1 and 2. The singleton is created lazily the first time nextId is called, its next counter starts at 1, and next++ hands out 1 then 2. The code is compact, and for a single batch it looks entirely correct.

The evening batch exposes the problem. Its orders come out as 3 and 4, not the intended 1 and 2, because IdGenerator is a single shared instance whose next counter persists across every call in the whole program. The morning batch left the counter at 3, and the evening batch simply continued from there. There is exactly one board, and both crews chalked on it.

This is the genuine design flaw: per-batch numbering was modelled with process-global singleton state. Because an object declaration has one instance for the program's lifetime, its mutable next field is shared by every caller, silently coupling batches that were meant to be independent. The output is deterministic here only because the two batches run in sequence; run them concurrently and the shared next++ becomes an outright data race with unpredictable ids. The fix is to stop using a singleton for state that is not truly global: make the generator an ordinary class and give each batch its own instance (val gen = IdGenerator2(); items.map { gen.nextId() }), or thread a generator parameter through processBatch. A singleton is the right tool for one shared fact, and the wrong tool the moment the "fact" is really per-caller.

Common Mistakes

  1. Storing per-request state in a singleton. An object has one instance for the whole program, so a mutable field on it is shared by every caller. Keep only truly global, ideally immutable, facts there.
  1. Assuming a singleton resets between logical scopes. A counter or cache in an object persists for the process lifetime; it does not restart per batch, per request, or per test. Use an instance when the state should be scoped.
  1. Treating a companion object as free static dispatch. Companion members compile to instance calls on a hidden singleton, not to JVM statics; annotate with @JvmStatic only when you specifically need a real static for Java interop.
  1. Believing a class can have several companions. A class has at most one companion object. Additional shared members must go into named nested objects instead.
  1. Forgetting an object declaration is lazy. Its initializer runs on first access, not at program start, so side effects in the initializer fire at an unpredictable moment. Do not rely on eager construction.
  1. Confusing an object expression with an object declaration. object : Iface { } builds a fresh anonymous instance each time it is evaluated; object Name { } builds one singleton. Only the expression form can close over local state.
  1. Using a singleton to dodge dependency injection. Reaching into a global object from deep in the code hides dependencies and makes testing hard. Pass collaborators in so they can be substituted.
  1. Mutating singleton state from multiple threads without synchronization. Shared mutable state on an object is a data race; guard it, make it immutable, or confine it to one thread.
  1. Putting constants in a companion when a top-level const val would do. A file-level const val is simpler and cheaper than a companion field for plain constants; reserve the companion for factories and members that belong to the class.

Best Practices

  • Keep singletons stateless or immutable; if an object must hold mutable state, treat that state as global and guard it accordingly.
  • Use a companion object for factory functions and class-level constants, hiding the constructor with private constructor when construction should go through the factory.
  • Model per-scope counters and caches as ordinary class instances, not singletons, so each scope gets its own state.
  • Reach for an object expression when you need a one-off implementation of an interface that captures local state; reach for a declaration when you need a named singleton.
  • Let a companion object implement an interface when the factory itself must satisfy a contract, rather than exposing loose top-level functions.
  • Prefer passing dependencies as parameters over reaching into global singletons, keeping code testable and its dependencies visible.
  • Remember that object initialization is lazy, and avoid ordering-sensitive side effects in an object initializer.
  • Use a top-level const val for simple compile-time constants instead of housing them in a companion.

Practice Exercises

  1. Declare an object Registry with a register(name: String) method and a count(). Call it from two different functions and confirm the count accumulates across both, demonstrating single shared state.
  1. Give a class a private constructor and a companion object factory that validates its argument before constructing. Show that direct construction does not compile but the factory does.
  1. Reproduce the shared-counter flaw: number two batches with a singleton generator and observe that the second batch does not restart at 1. Then refactor the generator into a per-batch instance and confirm both batches number from 1.
  1. Write a function that returns an anonymous object implementing an interface and closing over a local variable. Call the function twice and show that each call produces an independent instance with its own captured state.