Singleton in Kotlin

Update : Andrey Breslav approach is better for creating singleton in Kotlin

Kotlin doesn’t have static member for class, it’s mean that you can’t create static method and static variable in Kotlin class. So, how can we create 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" }
}             // This is factory
MyClass.getMoreInfo() // This is factory fun

Every properties and method inside 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.

Update : 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 ensure 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.
var first = Singleton.instance  // This (Singleton@7daf6ecc) is a
// singleton
first.b = "hello singleton"

var second = Singleton.instance
println(second.b) // hello singleton
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.