Junior
Tell me about the keyword Object in Kotlin and its application.
sobes.tech AI
Answer from AI
The keyword object in Kotlin is used for declaring:
- Object Singletons (Object Declarations): Creates a single instance of a class, accessible globally. Initialized upon first access.
- Companion Objects: Placed inside a class to declare static members (fields, methods). Allows access to them by class name without creating an instance.
- Anonymous Objects (Object Expressions): Creates an instance of an anonymous class, often used for implementing interfaces or extending other classes "on the fly".
// Singleton example
object AppConfig {
// singleton properties
const val API_URL = "https://example.com/api/"
}
// Companion object example
class MyClass {
// properties and methods of the companion object
companion object {
fun create(): MyClass {
// initialization logic
return MyClass()
}
}
}
// Example of using an anonymous object
interface ClickListener {
// interface method
fun onClick()
}
fun setupButton(listener: ClickListener) {
// using an anonymous object
val buttonClickListener = object : ClickListener {
override fun onClick() {
// method implementation
}
}
listener.onClick() // calling the passed listener
}