I want to make a copy of a case class, updating it with optional values from a second case class.
case class A(
id: Int,
a: String,
b: String,
c: String)
case class Update(
a: Option[String],
b: Option[String],
c: Option[String])
What is the most efficient way that I can make a copy of A
, updating the fields with values from Update
that are not None
? I want to avoid making a match/case statement involving all possible permutations of Some/None
values in Update
, if possible.
All case classes have a copy method.
http://docs.scala-lang.org/tutorials/tour/case-classes.html (find the copy term)
val a = A(1, "", "", "")
val update = Update(None, "scalaz".some, None)
val b = a.copy(
b = update.b.getOrElse(a.b)
)
Also check out the lens pattern for copying deeply nested objects in a functional manner:
http://eed3si9n.com/learning-scalaz/Lens.html
Once you have objects made up of other objects and so on, it becomes highly cumbersome to use the copy
method. Scalaz's lens pattern implementation is a great alternative.
Simply:
val originalA: A = // ...
val update: Update = // ...
val newA: A = A(
id = originalA.id,
a = update.a.getOrElse(originalA.a),
...
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With