How to Create Singleton in Kotlin: Simple Guide
In Kotlin, you create a singleton by using the
object keyword, which defines a class with only one instance. This instance is created lazily and is thread-safe by default, so you just use object MySingleton to define it.Syntax
The object keyword in Kotlin declares a singleton. It creates a class and its single instance at the same time. You don't need to write constructors or manage instance creation.
object MySingleton: Defines the singleton object.- Inside, you can add properties and functions like a normal class.
- Access members directly via
MySingleton.member.
kotlin
object MySingleton {
val name = "SingletonExample"
fun greet() = "Hello from $name"
}Example
This example shows a singleton that holds a counter and a greeting function. It demonstrates how to access and modify the singleton's properties.
kotlin
object CounterSingleton {
var count = 0
fun increment() {
count++
}
fun greet() = "Count is $count"
}
fun main() {
println(CounterSingleton.greet())
CounterSingleton.increment()
CounterSingleton.increment()
println(CounterSingleton.greet())
}Output
Count is 0
Count is 2
Common Pitfalls
Some common mistakes when creating singletons in Kotlin include:
- Trying to use a
classwith private constructors and manual instance management instead ofobject. - Assuming
objectinstances are created eagerly; they are lazy but thread-safe. - Using companion objects when a full singleton object is needed.
Using object is the simplest and safest way to create a singleton in Kotlin.
kotlin
/* Wrong way: manual singleton with class */ class ManualSingleton private constructor() { companion object { private var instance: ManualSingleton? = null fun getInstance(): ManualSingleton { if (instance == null) { instance = ManualSingleton() } return instance!! } } } /* Right way: Kotlin singleton */ object KotlinSingleton { fun greet() = "Hello from KotlinSingleton" }
Quick Reference
Summary tips for Kotlin singletons:
- Use
objectkeyword to create a singleton. - Access members directly via the object name.
- Singletons are thread-safe and lazily initialized.
- Use companion objects only for static-like members inside classes.
Key Takeaways
Use the Kotlin
object keyword to create a singleton easily and safely.Singleton objects are lazily initialized and thread-safe by default.
Access singleton members directly through the object name without creating instances.
Avoid manual singleton patterns with private constructors; Kotlin's
object is simpler.Use companion objects only for static members inside classes, not for full singletons.