Effective Kotlin: Item 1 — Consider static factory methods instead of constructors

As an alternative to public constructors Effective Java talks about using static factory methods such as from, of, valueOf, getInstance, newInstance and newType that return an instance of a class. See Joshua’s book for the pros and cons.

We see an example of this in the Android SDK with the Toast.makeText() function. Additionally, Alex Lockwood talks about using a Fragment.newInstance() pattern on Android which helps encapsulate the Bundle data. You may also come across Activity.newIntent().

Implementing in Kotlin is straightforward, the factory method is contained in a companion object within an interface as my example below shows or more traditionally in a class that has a private constructor. For interoperability with Java, ensuring the function appears as a static method, it is recommended to add the @JvmStatic annotation.

interface ImageReader {
fun read(file: File): Bitmap

companion object {
fun newImageReader(format: String) = when (format) {
"jpg" -> JpegReader()
"gif" -> GifReader()
else -> throw IllegalStateException("Unknown format")

While Kotlin allows adding extension functions to existing classes, this isn’t possible to do for Java classes or unless the existing Kotlin implementation already has a companion object until JetBrains implement KT-11968.

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store