Last Updated: February 25, 2016
· Jeroen Rosenberg

Update property value of immutable object while maintaining immutability

Let's say we have a case class Item with a few properties

case class Item(name:String, category:String, price:Double)

At a certain point in your app's lifecycle you might need to 'update' one of the properties of an instance of this case class. Say, for instance, we need to update the 'price' property. However, the Item object is immutable. Of course you can change that:

case class Item(name:String, description:String, var price:Double)

However, this is not very nice imho. Instead, Scala case classes allow us to clone the object and selectively change property values by using the copy method. For example:

val items = List(Item("Apple","Fruit", 1.50),Item("Pear", "Fruit", 2.00))
val items_on_sale = = 0.50))

This makes in very easy to make small transformations to your objects while maintaining immutability

2 Responses
Add your response

thank you really helpful :D i'm still in the process of learining scala

over 1 year ago ·

Thanks for you help!!
I found another way to do this.

Working with your example:
val items = List(Item("Apple","Fruit", 1.50),Item("Pear", "Fruit", 2.00))
val itemsonsale = items.copy(price = 0.50)

I'm in the process of learning scala too


over 1 year ago ·