Member-only story

Effective Kotlin: Item 3 — Enforce the singleton property with a private constructor or an enum type

Matthew Dolan
2 min readFeb 20, 2018

--

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.

object Singleton : Serializable {
//...

// The type must be specified as Any for this to work
private fun readResolve(): Any = Singleton
}

His final approach uses enums as this guarantees exactly one instance with no possibility of serialisation or reflection attacks. One thing to note, however, in doing this using object you access the singleton through Singleton.myFunction(), whereas the enum approach is more explicit, Singleton.INSTANCE.myFunction(), and not so Kotlin-esque.

enum class Singleton {
INSTANCE;

//...
}
Singleton.INSTANCE.myFunction()

If you are happy with the risks of someone creating a second instance of your Singleton, stick with the object Singleton declaration for its simplicity.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Join medium to read all of my articles or subscribe for e-mail updates.

--

--

Matthew Dolan
Matthew Dolan

Written by Matthew Dolan

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

No responses yet

Write a response