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

后端 未结 5 1559
难免孤独
难免孤独 2020-11-30 17:58

Let\'s say I have a case class that represents personas, people on different social networks. Instances of that class are fully immutable, and are held in immutable collecti

5条回答
  •  粉色の甜心
    2020-11-30 18:19

    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
    

提交回复
热议问题