Middle
What are 'object expressions' and 'object declarations' in Kotlin?
sobes.tech AI
Answer from AI
Object expressions (anonymous objects) are used to create objects of anonymous classes. They are useful for implementing one-time interfaces or inheriting from classes in a single instance. Syntax: object : <type(s)>.
Object declarations create a singleton. This is a class with a single instance that is globally accessible by its name. Syntax: object <name>.
Comparison table:
| Feature | Object expressions | Object declarations |
|---|---|---|
| Purpose | Creating an anonymous object | Creating a singleton |
| Usage | Local, inside expressions or functions | Public, by object name |
| Instance creation | Each time the expression is used | One instance upon first access |
| Naming | Anonymous | Named |
| Application | One-time event listeners, adapters | Utilities, configurations, state storage |
Example of object expression:
// Creating a click handler "on the fly"
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
// Action on click
}
})
Example of object declaration:
// Declaring a singleton object for logging
object Logger {
fun log(message: String) {
println(message)
}
}
// Using the singleton
fun processData(data: String) {
Logger.log("Processing data...")
// Data processing
}