Data Objects in Kotlin
<p>Data objects are a new Kotlin language feature introduced in version <code>1.7.20</code> and are currently planned to be released in version <code>1.9</code>. We’ll take a closer look at what they are and what issue they are trying to solve.</p>
<h2>What issue are data objects solving?</h2>
<p>Below we have a typical example of a sealed class hierarchy where we are using a <code>sealed interface</code> (we could also use a <code>sealed class</code>) to define possible states for a Profile screen. We are using a <code>data class</code> for the success state and an <code>object</code> for error and loading states since we don’t need any additional information.</p>
<p>What if we want to log/print the current screen state for either debugging reasons or for sending it to an analytics service? The string representation of the <code>ProfileScreenState.Success</code> data class contains the name of the class and all its properties, which is exactly what we want.<br />
But if we print a plain <code>object</code> declaration in Kotlin, we’ll get a string containing the full package name, object name, and the address of where this object is stored in memory. And since objects are singletons in Kotlin, the address part will remain the same each time we print that object and is not relevant to us.</p>
<pre>
com.dataobjects.example.ProfileScreenState$Loading@6d03e736
Success(username=exampleUser1)
com.dataobjects.example.ProfileScreenState$Error@5fd0d5ae</pre>
<p>One solution would be to override the <code>toString(): String</code> function on each object and provide our implementation, but that seems like a lot of boilerplate code for such a trivial issue.</p>
<p> </p>
<h2>Data objects</h2>
<p>Kotlin is planning to solve this using data objects. A <code>data object</code> is identical to a regular <code>object</code> but provides a default implementation of the <code>toString()</code> function that will print its name, removing the need to override it manually, and aligning behavior with a <code>data class</code> definition. They are especially useful for sealed class hierarchies to match behavior with data classes.</p>
<p><a href="https://medium.com/@domen.lanisnik/data-objects-in-kotlin-1a549bfad657">Click Here</a></p>