How do i create singleton object in kotlin?

Last updated Apr 24, 2021

In this Kotlin programming example we will learn how to create a singleton class in kotlin. In kotlin singleton class is nothing but a singleton object. The known factor is that singleton class is nothing but it contains a single instance. So in kotlin if we want to create a single instance of the class then we will denote the class as object with the name of the class.

 

Let's create an object for a kotlin class MySingleTon

// Kotlin program
fun main(args: Array<String>)
{
    val obj1 = MySingleTon()
    val obj2 = MySingleTon()
    println(obj1.toString())
    println(obj2.toString())
}

class MySingleTon
{

}

 

Output:

MySingleTon@135fbaa4
MySingleTon@45ee12a7

 

When we run the above program it will print two different address for the class MySingleTon object, that means it is wasting the memory.

 

Now change the above class declaration with 'object' keyword

fun main(args: Array<String>)
{

    println(MySingleTon.toString())
    println(MySingleTon.toString())
}

object MySingleTon
{

}

Here we defined the class MySingleTon with the "object" so it always contains a single instance.

Output

MySingleTon@135fbaa4
MySingleTon@135fbaa4

 

That means when we use 'object' instead of 'class' kotlin will use singleton and use single memory for the all instances. Kotlin "object" contains properties, methods, and init block. For the Object there is no way of constructor property. So if we want to initialize any properties of variables we can use init{} block.

 

Kotlin Singleton class with init block

// Kotlin program
fun main(args: Array<String>)
{

    println(MySingleTon.name)
    println("Addition of two Number ${MySingleTon.add(12,22)}")
}

object MySingleTon
{

    var name="MySingleTon"
    init
    {
        println("Singleton class invoked.")
    }

    fun add(a:Int,b:Int):Int
    {
        return a.plus(b)
    }
}

 

Output:

Singleton class invoked.
MySingleTon
Addition of two Number 34

 

The init{} block will take first place while run the program.

 

Properties of Singleton class Kotlin Object properties

Single Instance: Object class always be contain a single instance and will use single memory for entire application

Global Access: Object class should be global accessible, so the class can use it

Constructor Not allowed: For Object class can't use constructor, we can use ini{} block to initialize the variables and other methods

 

Conslusion: In this post we cover how to create singleton in kotlin and what is "object", how to use init{} block to initialize the properties without constructor of the class.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

746 Views