Here is my code::
data class User(val id: Int, name: String)
fun getUsers(): List<User>
Now, I want to add an age
field to the User data class, but I'm concerned about two things:
User
.I would love to hear from the community about the best approach to add a field to a data class returned by a function in Kotlin without breaking existing code and without adding unnecessary memory overhead.
Thank you!
One approach I thought of is adding the age 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)
fun getUsers(includeAge: Boolean = true): List<User>
However, I'm not sure if this approach solves the memory issue or not. Also, I'm considering the decorator approach, but I'm not sure if it's the best solution.
What exactly do you afraid of to be broken? Usually in case of Java it were equals()
+ hashCode()
methods that could be broken. But Kotlin generates these methods for data classes under the hood.
There is no exact answer to your question, because you provided too little information: which types of usage of this class there is in the project. Where you create this user: locally or just parsing some data which you receive from backend? What is business case?
If you're afraid to break some parts of the code, you probably better to get advice from your colleagues who've acquainted with the codebase or provide please more information.
In any case, based on the information you provided, I don't think that something can be broken after you'll add nullable optional parameter. Probably it will be the best solution.