Scala case class copy

We learned about case class in previous SKBs, but we haven't seen the full spectrum of features that this special structure offers.

One of the use case for this structure is to represent a row in a database. In some other languages, case class are even called Record.

We are now going to learn how to modify the values of the column of this record.

Introducing copy !

copy is this generated method that all case class have. It allows to make a copy of the case class instance while modifying zero, one, more or all the fields that the case class has.

Remember than in functional programming and in Scala, we want to only work with immutable entities. It would be very tedious to have to manually recreate the case class, which could have dozens of fields, when all we want is, for instance, to modify the last updated date. The is the reason for the method, copy.

But how does this magic mathod works !

Well, look at the method in the example called updateContent. You can see that the arguments have default values set for them. The trick is to use the current value of the fields of the case class as default value and voila!

Look at how it is used lower in the exercise, you can omit some of the arguments of the method, which means it will use the default value. This allow us to modify only the part we want and keep the rest the same.

Reveal more information and clues
Load Exercise