0

Kotlin – Singleton

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.
  • 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.

Singleton in Kotlin

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.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert