Software Development

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.

[wp_ad_camp_1]

Singleton in Kotlin

[wp_ad_camp_2]

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.

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like