How to Create Singleton Class in Kotlin?

Singleton is a global object that can be accessed from everywhere in your application. This article shows different ways of creating it in Kotlin.

ยท

2 min read

How to Create Singleton Class in Kotlin?

In Kotlin, you can use the object declaration to implement singleton. However, if you don't aware of this object keyword, you probably will do something like this.

Conventional Singleton

class Singleton private constructor() {

    companion object {
        @Volatile
        private lateinit var instance: Singleton

        fun getInstance(): Singleton {
            synchronized(this) {
                if (!::instance.isInitialized) {
                    instance = Singleton()
                }
                return instance
            }
        }
    }

    fun show() {
        println("This is Singleton class!")
    }
}

fun run() {
    Singleton.getInstance().show()
}
  • private constructor() is used so that this can't be created as usual class
  • @Volatile and synchronized() are used to make sure this Singleton creation is thread-safe.

Object Declaration Singleton

This can be simplified to

object Singleton {
    fun show() {
        println("This is Singleton class!")
    }
}

fun run() {
    Singleton.show()
}

Singleton is a class and also a singleton instance where you can access the singleton object directly from your code.

Constructor Argument Singleton

The limitation of this object declaration is you can't pass a constructor parameter to it to create the singleton object. If you want to do that, you still need to use back the first conventional method above.

class Singleton private constructor(private val name: String) {

    companion object {
        @Volatile
        private lateinit var instance: Singleton

        fun getInstance(name: String): Singleton {
            synchronized(this) {
                if (!::instance.isInitialized) {
                    instance = Singleton(name)
                }
                return instance
            }
        }
    }

    fun show() {
        println("This is Singleton $name class!")
    }
}

fun run() {
    Singleton.getInstance("liang moi").show()
}

Conclusion

I personally use singleton for simple utility class (use object declaration) and database (use convention singleton method - because it is required to pass in argument).

Did you find this article valuable?

Support Vincent Tsen - AndroidDev Blog by becoming a sponsor. Any amount is appreciated!

ย