Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case class copy with optional values

Tags:

scala

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.

like image 737
Jacob Lyles Avatar asked Dec 10 '22 12:12

Jacob Lyles


2 Answers

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.

like image 167
Quy Avatar answered Dec 27 '22 10:12

Quy


Simply:

val originalA: A = // ...
val update: Update = // ...
val newA: A = A(
  id = originalA.id,
  a = update.a.getOrElse(originalA.a),
  ...
)
like image 31
Jean Logeart Avatar answered Dec 27 '22 11:12

Jean Logeart