0
0
KotlinConceptBeginner · 3 min read

What is Singleton in Kotlin: Simple Explanation and Example

In Kotlin, a singleton is a design pattern that ensures a class has only one instance throughout the app. You create it using the object keyword, which automatically handles instance creation and thread safety.
⚙️

How It Works

A singleton in Kotlin is like having a single, special tool in your toolbox that you always use instead of making many copies. When you declare a class as an object, Kotlin creates one instance of it automatically and shares it everywhere you need it.

This means you don't have to create new objects manually or worry about multiple copies causing confusion. The system guarantees that only one instance exists, and it is created the first time you use it, making it efficient and safe to use in different parts of your program.

💻

Example

This example shows a singleton object that counts how many times a function is called. The count is shared everywhere because there is only one instance.

kotlin
object Counter {
    var count = 0
    fun increment() {
        count++
        println("Count is now: $count")
    }
}

fun main() {
    Counter.increment()
    Counter.increment()
    Counter.increment()
}
Output
Count is now: 1 Count is now: 2 Count is now: 3
🎯

When to Use

Use a singleton when you need one shared resource or manager in your app, like a logger, configuration settings, or a connection pool. It helps avoid creating multiple instances that could cause inconsistent data or waste memory.

For example, if you want to keep track of app-wide settings or share a cache, a singleton ensures all parts of your app see the same data and state.

Key Points

  • Kotlin uses the object keyword to create singletons easily.
  • Singletons have only one instance shared across the app.
  • They are created lazily and are thread-safe by default.
  • Useful for shared resources like settings, logging, or caches.

Key Takeaways

Singletons in Kotlin are created with the object keyword and have only one instance.
They provide a shared, consistent resource accessible from anywhere in the app.
Singletons are thread-safe and created only when first used.
Use singletons for global managers like logging, configuration, or caching.