-
Notifications
You must be signed in to change notification settings - Fork 23
Kotlin: Object Class vs Data Object Class
Devrath edited this page Aug 8, 2024
·
1 revision
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:
-
Singleton: The
object
keyword 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
object
is initialized lazily, the first time it is accessed.
Example:
object MySingleton {
val name = "Singleton"
fun printName() {
println(name)
}
}
-
Singleton with Data Features: The
data object
is a specialized form of anobject
that 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 object
ensures 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"
}
- Use
object
when you need a simple singleton without automatic data class features. - Use
data object
when you want a singleton with the benefits of a data class, such asequals()
,hashCode()
, andtoString()
methods.