Singleton in Kotlin (Better Approach)

Today, I write a post about Singleton in Kotlin, and it is heavily influenced by Java style. Soon after that, Andrey Breslav (Kotlin language designer) give a response and a better approach to write a Singleton in Kotlin.

My mistake is I didn’t realize that object can have initialization logic. That’s why I think that class is better approach than using object.

So, this is the rewrite of my first singleton version :

object Singleton {
init {
println("This ($this) is a singleton")
}

var b:String? = null
}
var first = Singleton    //This (Singobj@728938a9) is a singleton
first.b = "hello singleton"
var second = Singleton
println(second.b) //hello singleton

More compact, readable and robust :) thank you Mr. Andrey Breslav.

One clap, two clap, three clap, forty?

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