Questions
KotlinIntermediate4 min
Singleton Pattern in Kotlin with object keyword?
Answer
In Kotlin, the `object` keyword is the idiomatic way to create a Singleton.
Features
- Thread Safety: It is thread-safe by default. The instance is created lazily when the class is first accessed.
- Simplicity: No need for static blocks, double-checked locking, or private constructors.
```kotlin object Database { val name = "MainDB" fun connect() { ... } }
// Usage Database.connect() ```
Under the hood, it compiles to a Java class with a static `INSTANCE` field.
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚