Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a case class instance and change just one field in Scala?

Tags:

scala

case classcomes with a copy method that is dedicated exactly to this usage:

val newPersona = existingPersona.copy(sentMessages = 
                   existingPersona.sentMessages + newMessage)

Since 2.8, Scala case classes have a copy method that takes advantage of named/default params to work its magic:

val newPersona =
  existingPersona.copy(sentMessages = existing.sentMessages + newMessage)

You can also create a method on Persona to simplify usage:

case class Persona(
  svcName  : String,
  svcId    : String,
  sentMsgs : Set[String]
) {
  def plusMsg(msg: String) = this.copy(sentMsgs = this.sentMsgs + msg)
}

then

val newPersona = existingPersona plusMsg newMsg

existingPersona.copy(sentMessages = existingPersona.sentMessages + newMessage)