Open dvas0004 opened 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
A typical java-like singleton would look like this in Kotlin:
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:
We simply got rid of the private SingletonHolder object, Furthermore, Kotlin shorthands all this to a single line:
object Singleton