Kotlin Objects

Creating single instances and singletons

🎯 What are Objects?

Objects in Kotlin are single instances that exist only once in your program. Unlike classes that can create multiple instances, objects are singletons - perfect for utilities and shared resources.


// Object declaration - only one instance exists
object MathUtils {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
    
    fun multiply(a: Int, b: Int): Int {
        return a * b
    }
}
                                    

Usage:

val result = MathUtils.add(5, 3)
println(result) // 8

Key Object Concepts

🏆

Singleton

Only one instance exists

object Database { }
🔧

Utility Functions

Shared helper methods

object Utils { fun format() }
📊

Companion Objects

Objects inside classes

companion object { }
🎭

Anonymous Objects

Objects without names

object : Interface { }

🔹 Object Declaration

Create a singleton object that can be used throughout your program:

object Logger {
    private var logCount = 0
    
    fun log(message: String) {
        logCount++
        println("[$logCount] $message")
    }
    
    fun getLogCount(): Int {
        return logCount
    }
}

fun main() {
    Logger.log("Application started")
    Logger.log("User logged in")
    Logger.log("Data saved")
    println("Total logs: ${Logger.getLogCount()}")
}

Output:

[1] Application started
[2] User logged in
[3] Data saved
Total logs: 3

🔹 Companion Objects

Objects inside classes that can be called without creating an instance:

class Person(val name: String, val age: Int) {
    
    companion object {
        private var personCount = 0
        
        fun createChild(name: String): Person {
            personCount++
            return Person(name, 0)
        }
        
        fun createAdult(name: String): Person {
            personCount++
            return Person(name, 18)
        }
        
        fun getTotalPeople(): Int {
            return personCount
        }
    }
    
    fun introduce() {
        println("Hi, I'm $name, age $age")
    }
}

fun main() {
    val child = Person.createChild("Tommy")
    val adult = Person.createAdult("Sarah")
    
    child.introduce()
    adult.introduce()
    println("Total people created: ${Person.getTotalPeople()}")
}

Output:

Hi, I'm Tommy, age 0
Hi, I'm Sarah, age 18
Total people created: 2

🔹 Anonymous Objects

Create objects on-the-fly without declaring a class:

interface ClickListener {
    fun onClick()
}

fun main() {
    // Anonymous object implementing an interface
    val button = object : ClickListener {
        override fun onClick() {
            println("Button was clicked!")
        }
    }
    
    // Anonymous object with custom properties
    val config = object {
        val appName = "MyApp"
        val version = "1.0"
        fun getInfo() = "$appName v$version"
    }
    
    button.onClick()
    println(config.getInfo())
}

Output:

Button was clicked!
MyApp v1.0

🔹 Object vs Class

Understanding when to use objects vs classes:

// Use CLASS when you need multiple instances
class Car(val brand: String) {
    fun start() = println("$brand starting...")
}

// Use OBJECT when you need only one instance
object CarFactory {
    private var carsProduced = 0
    
    fun createCar(brand: String): Car {
        carsProduced++
        println("Producing car #$carsProduced")
        return Car(brand)
    }
}

fun main() {
    // Multiple car instances
    val car1 = CarFactory.createCar("Toyota")
    val car2 = CarFactory.createCar("Honda")
    
    car1.start()
    car2.start()
    
    // Only one CarFactory exists
}

Output:

Producing car #1
Producing car #2
Toyota starting...
Honda starting...

🧠 Test Your Knowledge

How many instances of an object can exist in Kotlin?