October 2019
Intermediate to advanced
434 pages
11h 54m
English
To create thread-safe Singletons in Kotlin, we can rely on object declarations, as we discovered in Chapter 5, Modeling Real-World Data. To create a Kotlin equivalent implementation of our ThreadSafeSingleton example from the previous section, we can write the following Kotlin code:
object ThreadSafeSingleton
With this single line, we can now access ThreadSafeSingleton from anywhere in our code base in a thread-safe manner. Adding the object keyword rather than class ensures that the compiler will generate bytecode that enforces the Singleton pattern for us.
We can now add a property to our ThreadSafeSingleton object to demonstrate how to access properties of an object declaration. Consider the ...
Read now
Unlock full access