Kotlin Basics - object aka Singleton

Kotlin Basics - object aka Singleton

A singleton class is a user-defined class in a way that only one instance of the class can be created and used everywhere.

Without a singleton, creating two different objects allocates two different object memories

In Kotlin, Singelton is made by using object keyword as follows

fun main(){

    println(Database) // prints Database@1c20c684
    val db = Database.getDatabaseName()
    println(db) // prints info.db
    println(Database) // prints Database@1c20c684
}

object Database{

    init {
        println("Database created")
    }

    private const val DATABASE_NAME = "info.db"

    fun getDatabaseName() = DATABASE_NAME

}

As you can see, the Database address is the same for two different calls in the above code

Things to note :

  • an object class can have functions, properties and an init block

  • the constructor method is not allowed

  • properties and functions are called using the class name as we do in the companion object

Please leave your comments to improve.

Enjoy and happy coding