Data Objects in Kotlin

<p>Data objects are a new Kotlin language feature introduced in version&nbsp;<code>1.7.20</code>&nbsp;and are currently planned to be released in version&nbsp;<code>1.9</code>. We&rsquo;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&nbsp;<code>sealed interface</code>&nbsp;(we could also use a&nbsp;<code>sealed class</code>) to define possible states for a Profile screen. We are using a&nbsp;<code>data class</code>&nbsp;for the success state and an&nbsp;<code>object</code>&nbsp;for error and loading states since we don&rsquo;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&nbsp;<code>ProfileScreenState.Success</code>&nbsp;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&nbsp;<code>object</code>&nbsp;declaration in Kotlin, we&rsquo;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&nbsp;<code>toString(): String</code>&nbsp;function on each object and provide our implementation, but that seems like a lot of boilerplate code for such a trivial issue.</p> <p>&nbsp;</p> <h2>Data objects</h2> <p>Kotlin is planning to solve this using data objects. A&nbsp;<code>data object</code>&nbsp;is identical to a regular&nbsp;<code>object</code>&nbsp;but provides a default implementation of the&nbsp;<code>toString()</code>&nbsp;function that will print its name, removing the need to override it manually, and aligning behavior with a&nbsp;<code>data class</code>&nbsp;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>
Tags: Data Kotlin