Junior — Middle
In what situations in Kotlin are objects used instead of classes or data classes?
sobes.tech AI
Answer from AI
In Kotlin, an object is used in the following situations:
- Singleton: when a single instance of a class is needed throughout the application. Declaring it with
objectguarantees that the object is created only once and is globally accessible. - Companion objects: for creating static members inside a class.
- Anonymous objects: for creating objects without an explicit class, for example, when implementing interfaces.
Unlike a regular class, an object cannot be instantiated multiple times, and a data class is intended for storing data with automatically generated methods equals, hashCode, toString.
Example of a singleton:
object DatabaseConfig {
val url = "jdbc:mysql://localhost:3306/mydb"
val user = "root"
val password = "password"
fun connect() {
// connection logic
}
}
Such an object is convenient to use when you need to centrally store settings or common functions.