Kotlin Singleton Example
To create an Singleton in Kotlin is very simple. All you need is to declare the class with the keyword object. The init block to initialize anything that you need for the Singleton class. @Synchronized for thread safe operations.
object MySingleton { var counter = 0 private set init { counter = 1 } @Synchronized fun addToCounter(num:Int) { counter = counter + num } }
References:
https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations
https://antonioleiva.com/objects-kotlin/
https://stackoverflow.com/questions/40398072/singleton-with-parameter-in-kotlin
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts