Kotlin - Singleton Object Expression

What is Singleton?

Singleton is an Object Oriented pattern, where class can have only one instance
To create a singleton for a class in Kotlin by Object declaration feature, for this we will use object keyword



object SingletonSample {

    // body of class

}

an object declaration can have state and behaviour. We can call this by . notation



Read What is a companion object in kotlin



Example


object Sample {
    private var a: Int = 0
    var b: Int = 1
    fun callInt(): Int {
        a = a+12
        return a
    }
}
fun main(args: Array) {
    val result: Int
    result = Sample.callInt()
    println("b = ${Sample.b}")
    println("result = $result")
}

While run the above program the output will be


b = 1
result = 12


Example 2


open class Animal() {
    fun eat() = println("Eat Food")
    fun work() = println("Few Animals Do work for human")
    open fun giveMilk() = println("Animals can give Milk?")
}
fun main(args: Array) {
    val animal = object : Animal() {
        override fun giveMilk() = println("Cow gives Milk")
    }
    animal.eat()
    animal.work()
    animal.giveMilk()
}

While run the above program the output will be


Eat Food
Few Animals Do work for human
Cow gives Milk


Example 3:


If an implementing class contains constructor with arguments then


open class Animal(type:String) {
    var anim=type;
    fun eat() = println("Eat Food")
    fun work() = println(anim+" Do work for human")
    open fun giveMilk() = println("$anim can give Milk?")
}
fun main(args: Array) {
    val animal = object : Animal("Cow") {
        override fun giveMilk() = println("Cow gives Milk")
    }
    animal.eat()
    animal.work()
    animal.giveMilk()
}


While run the above program the output will be


Eat Food
Cow Do work for human
Cow gives Milk

Subscribe For Daily Updates