Effective Kotlin: Item 4 — Enforce noninstantiability with a private constructor

Item 4 of Effective Java discusses enforcing non-instantiability of, generally, utility classes. Using Kotlin’s Object declarations allows us to implement the Singleton pattern with ease, item 3 has more details, but this isn’t the only approach to utility classes in Kotlin.

Examples of utility classes in Java consist of Math and Arrays. In Android, most people will have come across Log and TextUtils.

In Kotlin, unquestionably you can create a private constructor to stop instantiation of a class, but you have to ask yourself whether a traditional style utility class makes sense.

class DontCreateMe private constructor()

Instead, with Kotlin’s extension functions your utility functions apply directly to the objects they relate. So, instead of TextUtils.isEmpty() a better implementation would be fun CharSequence.isEmpty(), which incidentally is already in the Kotlin standard library. To improve interoperability with Java code, you add the @file:JvmName annotation to the top of the file.

@file:JvmName("SnackbarUtils")

import android.support.annotation.ColorInt
import android.support.design.widget.Snackbar

fun Snackbar.setBackgroundColor(@ColorInt color: Int) {
view.setBackgroundColor(color)
}

In a code base with both Java and Kotlin, it is important to note that the byte-code generated shows these top-level functions wrapped in a class that is instantiable from Java code against Joshua’s guidelines, this isn’t the case from the Kotlin side. Object declarations (i.e. singleton) are non-instantiable from both Java and Kotlin, although I would still favour top-level extension functions.

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.

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

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