androidengineers.Book a session
โ† All interview questions
KotlinIntermediate4 min

Singleton Pattern in Kotlin with object keyword?

Answer

In Kotlin, the object keyword is the idiomatic way to create a Singleton.

Features

  • Thread Safety: It is thread-safe by default. The instance is created lazily when the class is first accessed.
  • Simplicity: No need for static blocks, double-checked locking, or private constructors.
object Database {
    val name = "MainDB"
    fun connect() { ... }
}

// Usage
Database.connect()

Under the hood, it compiles to a Java class with a static INSTANCE field.

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising