Hi everyone :slightly_smiling_face: I wanted to un...
# getting-started
d
Hi everyone 🙂 I wanted to understand what is the best way to add information to the data class that is returned by a function without breaking code that already uses the function. For example
fun getUsers(): List<User>
data class User(val id: Int, name: String)
Now I want to add an
age
field as well. But if I add I have 2 problems - I can break the code of users who use the
User
construct, in addition - I load the memory (?) while information the user did not intend to request. What I was thinking of doing is adding the field with a default null and then adding the information always (or based on an optional argument in the
getUsers
function)
data class User(val id: Int, name: String, age: Int? = null)
But it doesn't solve the memory (or does it? How much does null takes?..) Another option is the decorator method, but here only those who hear about the new class will benefit. The existing class will remain ageless. In short - I would love to hear what options are available to me and what are the popular recommendations.. Thanks 🙂
f
by using a
data class
you've backed yourself into a corner. If you intend this to be part of a public API, you should use regular classes and provide a factory method or builder pattern to instantiate the class. `data class`es come with copy, destructuring and other properties that make them binary incompatible when you make changes as described in your post
👍 1
a
there’s a new-ish guide in the Kotlin docs for library authors, and data classes are covered https://kotlinlang.org/docs/jvm-api-guidelines-backward-compatibility.html#don-t-use-data-classes-in-api
👍 1
c
There's also an older blog post about this: https://jakewharton.com/public-api-challenges-in-kotlin/
👍 1