How to Create Singleton Class in Kotlin?

vtsen

Vincent Tsen

Posted on June 11, 2022

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.

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()
}
Enter fullscreen mode Exit fullscreen mode
  • 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()
}

Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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


Originally published at https://vtsen.hashnode.dev.

💖 💪 🙅 🚩
vtsen
Vincent Tsen

Posted on June 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related