This post demonstrates how to create a Singleton object in Kotlin
.
Requirements
IntelliJ
IDEA
Ultimate 2016.3- The
Community Edition
may be enough but we have not tried it.
- The
Kotlin
Version 1.1- Windows 10 Enterprise
Singleton in Java
In Java
, there is no straight-forward construct to create a Singleton
object. Normally, we would have a private constructor, and a thread-safe static method to retrieve a private instance of the class from which to invoke appropriate thread-safe methods. Consider the following example.
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import java.util.HashMap; import java.util.Map; public class Singleton { private static volatile Singleton singleton; private Map<String, String> map = new HashMap<>(); private Singleton() {} public static Singleton getInstance() { if(singleton == null) { synchronized(Singleton.class) { singleton = new Singleton(); } } return singleton; } public synchronized String getValue(String key) { return map.get(key); } public synchronized void setValue(String key, String value) { map.put(key, value); } public static void main(String[] args) { Singleton s = Singleton.getInstance(); s.setValue("app.settings.name", "Singleton Demo"); s.setValue("app.settings.version", "1.0"); System.out.println(s.getValue("app.settings.name")); System.out.println(s.getValue("app.settings.version")); } } |
Singleton in Kotlin
[wp_ad_camp_2]
In Kotlin
, there is a keyword object
used to create a Singleton
object of a class. Consider the example below. The keyword class
is replaced with the keyword object
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | object Singleton { private var map: HashMap<String, String> = HashMap() @Synchronized fun getValue(key: String): String? { return this.map.getValue(key) } @Synchronized fun setValue(key: String, value: String) { map.put(key, value) } } fun main(args: Array<String>) { Singleton.setValue("app.settings.name", "Singleton Demo") Singleton.setValue("app.settings.version", "1.0") println(Singleton.getValue("app.settings.name")) println(Singleton.getValue("app.settings.version")) } |
[wp_ad_camp_3]