0
0
KotlinConceptBeginner · 3 min read

What is Object Declaration in Kotlin: Simple Explanation and Example

In Kotlin, 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.

kotlin
object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}

fun main() {
    Logger.log("App started")
    Logger.log("An error occurred")
}
Output
Log: App started 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 new or a constructor.
  • Useful for utilities, managers, or shared resources.
  • Ensures only one instance exists in the program.

Key Takeaways

Object declaration in Kotlin creates a single, shared instance automatically.
It simplifies code by removing the need for explicit class instantiation.
Use it for utilities, managers, or any resource that should have only one instance.
The declared object can have properties and functions just like a class.