Concise way to copy objects in Scala
1 answer
Class types define not only methods equals
, hashCode
and toString
, but also copy
. Fortunately, the method copy
is defined in such a way that the object this
's current values are the default parameters, but you can change any of them using named arguments. Your example would look like this:
case class Type(
x : int,
y : int,
z : int,
)
val v = Type(x = 1, y = 2, z = 3)
v.copy(z=42)
But you can also use one of the lensing libraries. (I think both skalaz and shapeless have one.)
+6
source to share