Singleton Pattern in Kotlin
Introduction
Singleton Pattern is a fundamental concept every Kotlin developer should understand. Object declarations and companion objects provide singletons, factory methods, and static-like members without the ceremony of Java static blocks.
Singleton ensures only one instance of a class exists. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Singleton ensures only one instance of a class exists.
- Kotlin object declaration provides singleton by default.
- It is thread-safe and concise.
Syntax
object Config { val appName = "Demo" }Singleton Pattern in Kotlin Example Program in Kotlin
object AppConfig {
const val APP_NAME = "Kotlin Learning"
}
fun main(args: Array<String>) {
println(AppConfig.APP_NAME)
}Sample Output
Kotlin LearningWhen to use
Use object for true singletons; use companion object for factory methods and constants tied to a class.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
const val APP_NAME = "Kotlin Learning"assigns or updates a value used later in the program. -
The
println(AppConfig.APP_NAME)statement writes a line to the console — this produces part of the sample output below. -
Singleton ensures only one instance of a class exists.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Singleton ensures only one instance of a class exists.
- Kotlin object declaration provides singleton by default.
- It is thread-safe and concise.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.