Immutable objects are recommended for use in Scala.
To update a field of immutable object, we can use case class copy function.
This way is good for simple cases, but think about deeper nested objects, it looks bad.
An example for a simple domain model:
This looks good. Then we want to update a field of Address
Look not so good if more level of nested objects
Then LENS to the rescue. So what is LENS?
lenses are the pure functional equivalent of references (or pointers) to a sub-element of a complex data structure (or, rather, data value)
But how can we implement by this way to resolve the problem above?
We simply abstract the way of accessing/mutating a field of type V on an object of type O as following:
Want to access/mutate fields of an object?
But how about accessing/mutating fields of nested objects -> We need a Lens[Company, String].
Actually, this can be composed of companyAddrLens and addressNoLens using the following function:
Finally, there are many Lens libraries out there such as Monocle or Scalaz
For example, with Monocle, just declare the dependency in build sbt, then import classes for use: