October 2019
Intermediate to advanced
434 pages
11h 54m
English
Kotlin makes it easy to implement a singleton. If you aren't familiar with this, a singleton is an object that is only instantiated once for an application. We will explore the singleton pattern specifically in more detail in Chapter 17, Practical Design Patterns.
To quickly implement a singleton in Kotlin, we can use an object declaration that uses the object keyword to define a singleton class. In this code, SettingsManager is defined using an object declaration and is a publicly available singleton:
object SettingsManager : SettingsProvider { val map = HashMap<String, String>() fun printSettings() = map.forEach { println(it) } override fun getSetting(key: String) = map.getOrDefault(key, "default")}
Note that object declarations ...
Read now
Unlock full access