M2 · Separating Object CreationSession 4-5CreationalKotlin replaces itOutline

Intent. Force a class to have exactly one instance and give it a global access point.

In Kotlin. object declaration – thread-safe and lazily initialized, which is exactly what makes it too easy.

The pattern its own authors came to regret: global state that tests cannot replace. Kotlin’s object reduces it to a single keyword, which makes it more dangerous, not less. Half of this session is about when to reach for dependency injection instead.

Structure

classDiagram
    class Singleton {
        -instance$ Singleton
        -Singleton()
        +getInstance()$ Singleton
        +operation()
    }
    note for Singleton "Global state. Cannot be substituted in tests."