I was writing these 3 Game States inside a Sealed class:
sealed class Status {
object Idle : Status()
object Active : Status()
object GameOver : Status()
}
The IDE is suggesting I should use a data object
instead of object
.
The problem is that I have never heard of data object
. I looked around and did not find a solid explanation in relation to data object
. For instance, this 2015 answer suggests this is a bug!
I am looking for your thinking about data object
and its usages.
I eventually found some solid info on Data Objects from the Kotlin Docs
When you precede an ordinary object with data modifier
you are simply adding some features similar to those of Data Classes to the plain object. For instance a toString()
is automatically generated for you such that when you print data object
you get human readable name of the class without @address.
The docs do indeed recommend using a data objects
to go along with data classes in your sealed class.
data object declarations are a particularly useful for sealed hierarchies, like sealed classes or sealed interfaces, since they allow you to maintain symmetry with any data classes you may have defined alongside the object:
In summary adding data
modifier enhances a plain object to have toString()
, equals()/hashCode() pair
under the hood. The enhanced object will then match the workings of Data Classes
in the sealed class hierachy.
NB - Unlike the data classes, data object don't have copy()
- objects are singletons with one instance - and componentN()
- objects don't have properties and cannot be destructured - functions