Kotlin Singleton with Object Declaration

In object oriented programming, there is a common situation when you want a class to have only one instance. In Java, we usually implement using the Singleton Design Pattern: define a class with a private constructor and a static field holding the only existing instance of that class. This tutorial shows you a way to implement Singleton with Kotlin Object Declaration.

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

Kotlin provides object declaration feature with keyword object.

We use object keyword in several cases, but they all have the same core idea:
– defines a class, and at the same time
– creates an instance (an object) of that class

Like a class, an object declaration can contain declarations of properties, methods

But constructors are not allowed. Object declarations are created immediately at the point of definition, not through constructor. So defining a constructor in this case doesn’t make sense.

Object declarations can also inherit from class and interface.

You can call methods and access properties simply:

III. Practice

1. Object Declaration

2. Run & Check Result

Result:

By JavaSampleApproach | August 30, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*