Scala case class copy

We learned aboutcase classin 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 classare even calledRecord.

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

Introducingcopy!

copyis this generated method that allcase classhave. It allows to make a copy of the case class instance while modifying zero, one, more or all the fields that thecase classhas.

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 thelast 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 calledupdateContent. 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