Table of content

kotlin Singleton Pattern

Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Kotlin doesn't have static members for class, it means that you can't create a static method and static variable in Kotlin class. So, how can we create a singleton class in Kotlin?

Fortunately, Kotlin object can handle this. Specific to class, companion object keyword is used for its member to be accessible.

class MyClass {
  companion object Factory {
    val info = "This is factory"
    fun getMoreInfo():String { return "This is factory fun" }
  }
}
MyClass.getMoreInfo()

Every properties and method inside the companion object can be called directly by using class name (sounds like static eh.). And now, we can create a singleton class based on initialization-on-demand holder pattern.

use object instead

public class Singleton private constructor() {
    init { println("This ($this) is a singleton") }

    private object Holder { val INSTANCE = Singleton() }

    companion object {
        val instance: Singleton by lazy { Holder.INSTANCE }
    }
    var b:String? = null
}
  • private constructor is used to ensuring this class can’t be initialized anywhere except inside of this class.
  • init will be called when this class is initialized the first time i.e. when Singleton.instance called the very first.
  • Holder object & lazy instance is used to ensure only one instance of Singleton is created.

The output of the Singleton pattern in kotlin

var first = Singleton.instance  // This (Singleton@7daf6ecc) is a
                                // singleton
first.b = "hello singleton"

var second = Singleton.instance
println(first.b)        // hello singleton
println(second.b)        // hello singleton
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions