In Kotlin we have this notion of immutable properties.
I once heard that in functional programming, state should not be changed. I have been thinking about this in the context of domain models.
Let's say we have a Person
class (please don't mind this very silly and unrealistic example).
class Person(val firstName: String, val lastName: String, val age: Int)
Everything property is immutable, which is nice.
Now someone comes along and asks to replace the first name. So I create a function that can do this.
fun replaceFirstName(person: Person, newFirstName: String): Person {
return Person(newFirstName, person.lastName, person.age)
}
Now this looks really ugly to my eyes. In this case there are only 3 properties, of which one should be replaced. But you can probably imagine what this would look like in larger domain classes.
The easy thing would be to just replace the val
with a var
, but then the whole intention of immutability is gone.
I'm looking for something like this (it does throw an error since there is no copy function):
fun replaceName(person: Person, newFirstName: String): Person {
return person.copy { firstName = newFirstName }
}
Is there a nice and concise way to do this in Kotlin?
Kotlin has a concept of Data classes, which has copy
function you need. So if you'll declare your class as:
data class Person(val firstName:String, val lastName:String, val age:Int)
You'll be able to use this function. Also it will generate equals()/hashCode/toString()
for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With