0
0
Kotlinprogramming~5 mins

Why object declarations create singletons in Kotlin

Choose your learning style9 modes available
Introduction

Object declarations in Kotlin create singletons to ensure only one instance exists. This helps manage shared resources easily and safely.

When you need a single shared instance for configuration settings.
When you want to manage a single connection to a database.
When you want to create a utility class with functions but no need for multiple objects.
When you want to keep track of global state in your app safely.
Syntax
Kotlin
object ObjectName {
    // properties and functions
}

The object keyword creates a class and its single instance at the same time.

You do not need to create an instance manually; Kotlin does it for you.

Examples
This creates a singleton Logger with a log function.
Kotlin
object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}
This singleton holds configuration values shared across the app.
Kotlin
object Config {
    val url = "https://example.com"
    val timeout = 5000
}
Sample Program

This program shows how the singleton Counter keeps track of a count shared everywhere.

Kotlin
object Counter {
    var count = 0
    fun increment() {
        count++
    }
}

fun main() {
    Counter.increment()
    Counter.increment()
    println("Count is ${Counter.count}")
}
OutputSuccess
Important Notes

Object declarations are thread-safe by default, so you don't need extra code for safe access.

Because only one instance exists, you cannot create multiple objects from an object declaration.

Summary

Object declarations create a single instance automatically.

This singleton instance is shared everywhere in your program.

Use object declarations to manage shared data or utilities easily.