Kotlin

object Declaration — Singleton

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`object` declares a thread-safe lazy singleton. Built into the language — no `private constructor + getInstance()` boilerplate. Also: anonymous `object : Interface { … }` for one-shot instances.
Kotlin
Raw
object Database {
    private val cache = mutableMapOf<String, String>()

    fun put(k: String, v: String) { cache[k] = v }
    fun get(k: String): String? = cache[k]
    fun size() = cache.size
}

fun main() {
    Database.put("api_url", "https://api.example.com")
    println(Database.get("api_url"))            // https://api.example.com
    println(Database.size())                     // 1

    // Anonymous object — one-shot instance with interface override
    val handler = object : Runnable {
        override fun run() {
            println("running…")
        }
    }
    handler.run()

    // Anonymous object that captures from the enclosing scope
    var counter = 0
    val ticker = object {
        fun tick() { counter++; println("tick $counter") }
    }
    ticker.tick(); ticker.tick()
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.