What is Object Declaration in Kotlin: Simple Explanation and Example
object declaration is a way to create a singleton, which means a class with only one instance. It allows you to define an object directly without needing to create a separate class and then instantiate it.How It Works
Think of object declaration in Kotlin like having a single, special tool in your toolbox that you always want to use as is, without making copies. Instead of creating a class and then making an object from it, Kotlin lets you declare the object directly. This object is created once and shared everywhere.
This is useful when you want to have a single point of access for some functionality or data, like a manager or helper that doesn't need multiple copies. The object declaration handles creating and managing this single instance automatically.
Example
This example shows how to declare an object in Kotlin and use its function.
object Logger {
fun log(message: String) {
println("Log: $message")
}
}
fun main() {
Logger.log("App started")
Logger.log("An error occurred")
}When to Use
Use object declaration when you need a single instance of a class throughout your app. Common cases include:
- Logging utilities
- Configuration holders
- Singleton services or managers
This avoids creating multiple instances and keeps your code simple and clear.
Key Points
- Object declaration creates a singleton instance automatically.
- No need to instantiate with
newor a constructor. - Useful for utilities, managers, or shared resources.
- Ensures only one instance exists in the program.