Adding an item to a scala set, which is an IMMUTABLE map

I know there is a similar question, but I can not understand the solution to this problem (where I have an immutable card with an immutable set)

I have the following method, which aims to add an object of type Car to a set of Car objects. Case class with Map:

case class People( demo:Map[Person,Set[Car]] = Map() ) {

where each Car object has a name parameter of type person, and which has the following method, which is aimed at adding a car to a set of people, returning a new instance of People.

def +( c:Car ): People = {

The name variable in each car is related to which character the car should be attached to. This way, c.name can be used to retrieve the key where I should add the car. I.e.

var nameOfPerson  = c.name
demo(nameOfPerson) += c //Complains that += is not a member of Set

, , : scala,

, , , + = Set. :

People(demo + (c.name, c))

, (?,?), c.name..

P.S. , ,

+3
1
People(demo + (c.name, c))`

, (?,?), c.name..

+ Map, , "" . :

People(demo + ((c.name, c)))

People(demo + (c.name -> c))

c . :

case class People(demo: Map[Person,Set[Car]] = Map()) {
  def + (c: Car): People = {
    val oldSet = demo.getOrElse(c.name, Set.empty)
    val newSet = oldSet + c
    val newMap = demo + (c.name -> newSet)
    People(newMap)
  }
}
+8

All Articles