DEV Community

loading...

Kotlin Singleton with Object Declaration

loizenai profile image loizenai ・1 min read

https://grokonez.com/kotlin/kotlin-singleton-object-declaration

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


object Singleton {

    init {
        ...
    }

    var a: Int = ...

    fun doWork() {
        ...
    }
}

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:

More at:

https://grokonez.com/kotlin/kotlin-singleton-object-declaration

Kotlin Singleton with Object Declaration

Discussion (0)

Forem Open with the Forem app