Sobes.tech
Junior — Middle

How to implement the Singleton pattern in Kotlin and what features should be considered?

sobes.tech AI

Answer from AI

In Kotlin, the Singleton pattern is implemented very simply using the object keyword. This declaration creates a class with a single instance, which is lazily initialized and thread-safe by default.

Example of Singleton implementation:

object Database {
    fun query(sql: String) {
        println("Executing query: $sql")
    }
}

// Usage
Database.query("SELECT * FROM users")

Features:

  • No need to write code to control instance creation — everything is done automatically.
  • Thread-safe initialization without additional synchronization.
  • Can implement interfaces and inherit from classes.
  • If a lazy Singleton with parameters is needed, object is not suitable, and other approaches (like by lazy) are used.

Thus, in Kotlin, Singleton is simple and safe thanks to built-in support for object."}]}]}