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:

calculate(Singleton.a)
Singleton.doWork()

III. Practice

1. Object Declaration
package com.javasampleapproach.singleton

object Singleton {

	var message: String = "default Message"

	init {
		println("Initializing object: $this")
	}

	fun showSingleMessage() {
		println("Message: " + message)
	}

	fun setSingleMessage(message: String) {
		this.message = message
	}
}
2. Run & Check Result
package com.javasampleapproach.singleton

fun main(args: Array) {
	
	println("--- Singleton ---")
	println(Singleton.message)
	
	Singleton.showSingleMessage()
	Singleton.setSingleMessage("Hello Kolination!")
	
	println("--- singleton1 ---")
	val singleton1 = Singleton
	singleton1.showSingleMessage()
	Singleton.setSingleMessage("Hello Kolineer!")
	
	println("--- singleton2 ---")
	val singleton2 = Singleton
	singleton2.showSingleMessage()
}

Result:

--- Singleton ---
Initializing object: com.javasampleapproach.singleton.Singleton@232204a1
default Message
Message: default Message
--- singleton1 ---
Message: Hello Kolination!
--- singleton2 ---
Message: Hello Kolineer!


By grokonez | August 30, 2017.


Related Posts


Got Something To Say:

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

*