Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change state of an object in Kotlin with immutable properties

Tags:

kotlin

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?

like image 433
Johan Vergeer Avatar asked Jan 28 '23 21:01

Johan Vergeer


1 Answers

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.

like image 105
noktigula Avatar answered Jan 31 '23 09:01

noktigula