Search code examples
scalaimmutabilitycase-classseq

Scala how to append or remove item in Seq


I have following classes

case class User(userId: Int, userName: String, email: String,   
password:     
String) {
def this() = this(0, "", "", "")
}

case class Team(teamId: Int, teamName: String, teamOwner: Int,   
teamMembers: Seq[User]) {
def this() = this(0, "", 0, Nil)
}

I would like to add or User in teamMembers: Seq[User]. I tried couple of ways as:

Team.teamMembers :+ member
Team.teamMembers +: member

Nothing works :). Pleas advice me how can I add or remove item from teamMembers: Seq[User].

Thanks in advance!


Solution

  • You didn't mention which Seq do you use.

    If it's scala.collection.mutable.Seq you can add to this Seq.

    But, most changes that you use immutable.Seq which is Scala's default. This means you cannot add to a it, but you can create a new one with all items + new item.

    With scala out of the box you can do it like this -

      val team =Team(0,"", 0, Seq[User]())
      val member = User(0, "","", "")
    
      val teamWithNewMemebr = team.copy(teamMembers = team.teamMembers :+ member)
    

    But this becomes pretty ugly if you have a lot of nesting or you have to do it a lot.

    To overcome this complicated syntax you can use libraries like scalaz, monocle which provides you Lenses

    Here's a good sample of how to use Lenses http://eed3si9n.com/learning-scalaz/Lens.html