Concise way to copy objects in Scala

OCaml provides a concise syntax for copying records with many fields.

type t = {
  x : int;
  y : int;
  z : int;
}

let _ =
  let v = {x = 1; y = 2; z = 3} in
  {v with z = 42}

      

Is there a similar syntax for the Scala class classes?

+3


source to share


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







All Articles