Sobes.tech
Junior — Middle

How to implement the Singleton pattern in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the Singleton pattern is very simply implemented using the object keyword. This creates an object that is lazily initialized and guarantees a single instance.

Example:

object MySingleton {
    fun doSomething() {
        println("Performing an action")
    }
}

// Usage:
MySingleton.doSomething()

Such an object cannot be created multiple times, and it is automatically thread-safe.