Effective Kotlin: Item 3 — Enforce the singleton property with a private constructor or an enum type
There are a few different ways of enforcing the Singleton pattern in Java as suggested by Effective Java. Joshua Bloch goes into details of the pros and cons of each, so I recommend you take a look at his book.
Naively you could create a singleton by copying the Java pattern verbatim. However, Kotlin provides the Object declaration that makes it easy to declare. An object can extend other classes and interfaces.
object Singleton {
//...
}Singleton.myFunction()
Under the hood, the byte-code generates a public static final INSTANCE
field, similar to Joshua’s first documented approach and as such it is worth noting that this also means more than one instance can be created through reflection using the AccessibleObject.setAccessible
method. See Not so Singletons in Kotlin for a demonstration of this.
public final class Singleton {
public static final Singleton INSTANCE; static {
INSTANCE = new Singleton();
} //...
}
Also as Joshua points out if you wish for your singleton to be (Java) serializable, then you will need to implement a readResolve
method to return the only instance. Interestingly Kotlin’s serialisation library doesn't allow you to serialise an object
, complaining about a missing companion object.