Kotlin

How To Declare Singletons In Kotlin

Singleton is a very popular and widely used design pattern in software engineering. It restricts to have only one instance for a class. Singleton introduces a global state into an application.

Singleton is often implemented as a class in all object oriented programming languages. We are very familiar with the Singletons in Java programming language. But in Java, there is no in-built feature to create a singleton.

A singleton should be implemented with basic principles of a singleton design pattern and they are as follows,

Intent

  • Ensure a class has only one instance, and provide a global point of access to it.
  • Encapsulated “just-in-time initialization” or “initialization on first use”.

In other programming languages, the class is responsible for implementing the singleton behaviour. But in Kotlin, it is very easy to create a singleton. Kotlin language has built-in features for creating singletons.

To understand it better, let’s begin with creating a simple Singleton implementation.

Create A Singleton Kotlin class

Create a Kotlin class named “MySingleton.kt” and paste the below content.

object MySingleton {

var message = "This is a test message"    

    init {
        println("MySingleton class initialised.")
    }
    
    fun printMessage() {
        println(message)
    }
}

The above example shows a sample singleton implementation in Kotlin. Here only difference from a normal Kotlin class is the keyword “object” instead of keyword “class”. This is called Kotlin’s object declaration.

Kotlin’s Object Declaration

  • Object declaration is not an expression
  • Object declaration must have a name following object keyword.
  • Object declaration’s initialization is thread-safe.
  • Object declarations are initialized lazily, when accessed for the first time.

How To Access Singleton And It’s Methods

Let’s see how we can access this object and its members.

Create demo class named “DemoClass.kt” and add the following code into it.

class DemoClass {

   init {
        println("Class init method. Singleton message property :   ${MySingleton.message}")
        MySingleton.printMessage()
    }
}

Accessing the methods and properties in a singleton is same as in Java’s singleton class’s methods and properties.

  • [Classname]<dot operator>[methodName]
  • [Classname]<dot operator>[propertyName]

We can create any number of methods and properties inside an object declaration like in a normal Kotlin class.

Object With Supertype

It is possible to have a super type for an object expression. Example is given below,

object DefaultListener : MouseAdapter() { 
   override fun mouseClicked(e: MouseEvent) { ... } 
   override fun mouseEntered(e: MouseEvent) { ... } 
}

Create Object Declaration Inside A Class

It is possible to have an object declaration inside a class. To do this, we have to add “Companion”. Such objects are known as “Companion objects”

class DemoClass {

    companion object MySingleton {

var message = "This is a test message"    

    init {
        println("MySingleton class initialised.")
    }
    
    fun printMessage() {
        println(message)
    }
} 
}

Let’s see how we can call a companion object.

val instance = DemoClass.printMessage()

Or we can omit the name of companion object,

class DemoClass {
    companion object {} 
}
About author

Geethu is a teacher by profession, but she likes to research new things and is also interested in writing. Devdeeds is her blog, where she writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

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