Kotlin: Object Class vs Data Object Class - devrath/KotlinAlchemy GitHub Wiki
To understand a data object class, we need to understand what a data class is.
In Kotlin, the object and data object are both related to singleton objects, but they serve different purposes and have distinct features. Here's a comparison:
object
- Singleton: The
objectkeyword in Kotlin is used to create a singleton, which means only one instance of the class will exist. It's useful for creating single instances like utility classes or globally accessible objects. - No Automatic Methods: When you declare an
object, it doesn't automatically generate any methods likeequals(),hashCode(), ortoString(). You can override these methods if needed. - Initialization: The
objectis initialized lazily, the first time it is accessed.
Example:
object MySingleton {
val name = "Singleton"
fun printName() {
println(name)
}
}
data object
- Singleton with Data Features: The
data objectis a specialized form of anobjectthat also behaves like a data class. It automatically generatesequals(),hashCode(), andtoString()methods, making it more suitable when you want a singleton with data class-like behavior. - Immutability: Just like data classes,
data objectensures that the singleton is immutable, and its properties are generallyval. - Ideal for Use Cases: It's ideal for cases where the singleton holds state or is compared/used in collections.
Example:
data object MyDataSingleton {
val id = 1
val name = "DataSingleton"
}
Summary
- Use
objectwhen you need a simple singleton without automatic data class features. - Use
data objectwhen you want a singleton with the benefits of a data class, such asequals(),hashCode(), andtoString()methods.