0
0
Kotlinprogramming~5 mins

Object declaration syntax in Kotlin

Choose your learning style9 modes available
Introduction
Objects let you create a single instance with properties and functions to hold data or behavior, like a mini-toolbox you can use anywhere.
When you want to create a single shared instance for utility functions.
When you need a simple way to hold constants or configuration values.
When you want to group related functions and properties without making a class.
When you want to create a singleton that is used throughout your app.
Syntax
Kotlin
object ObjectName {
    // properties
    // functions
}
The object keyword creates a singleton instance automatically.
You don't need to create or call a constructor to use the object.
Examples
A simple object named Logger with a function to print messages.
Kotlin
object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}
An object holding constant values for configuration.
Kotlin
object Config {
    val maxUsers = 100
    val appName = "MyApp"
}
An object with a variable and a function to change it.
Kotlin
object Counter {
    var count = 0
    fun increment() {
        count++
    }
}
Sample Program
This program defines an object Greeter with a greet function. It calls greet twice with different names.
Kotlin
object Greeter {
    fun greet(name: String) {
        println("Hello, $name!")
    }
}

fun main() {
    Greeter.greet("Alice")
    Greeter.greet("Bob")
}
OutputSuccess
Important Notes
Objects are created when first used, so they are lazy initialized.
You can use objects to implement interfaces or extend classes if needed.
Objects are useful for grouping related code without needing multiple instances.
Summary
Use the object keyword to create a single instance with properties and functions.
Objects are great for utilities, constants, and singletons.
You access object members directly by the object name without creating instances.