dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Create Kotlin Singletons using delegated properties #106

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

A typical java-like singleton would look like this in Kotlin:

class Singleton private constructor() {

     private object SingletonHolder {
            val INSTANCE = Singleton()
     }

    companion object {
            val instance : Singleton by lazy {
                        SingletonHolder.INSTANCE
            }
    }

}

The above code:

The important note here is the "by lazy" delegate property. by lazy is thread safe and hence avoids the double check code we normally use in Java to create a singleton. In addition, the companion object is itself a singleton, so we can shorten the above to:

class Singleton private constructor() {

    companion object {
            val instance : Singleton by lazy {
                        Singleton()
            }
    }

}

We simply got rid of the private SingletonHolder object, Furthermore, Kotlin shorthands all this to a single line:

object Singleton

dvas0004 commented 5 years ago

https://medium.com/swlh/singleton-class-in-kotlin-c3398e7fd76b

Kotlin companion object as singleton: https://stackoverflow.com/questions/51834996/singleton-class-in-kotlin

Double check code: https://www.baeldung.com/java-singleton-double-checked-locking