I'm aware there is a similar question asked, but I can't figure out the solution to this problem ( Where I have an immutable map with an immutable set)
I have the following method, which aims to add an object of type Car to a set of Car objects. The case class with the Map is:
case class People( demo:Map[Person,Set[Car]] = Map() ) {
where every Car object has a name parameter of type person, and which has the following method that aims to add a car to the set of people, returning a new instance of People.
def +( c:Car ): People = {
The name variable in each car correlates to what Person the car should be mapped to. So c.name can be used to retrieve the key of where I should be adding the car. I.e.
var nameOfPerson = c.name
demo(nameOfPerson) += c //Complains that += is not a member of Set
I've tried adding this car in a plethora of ways, including the solution brought up in this problem: Adding element to a scala set which is a map value
But unfortunately, it keeps stating that value += is not a member of Set. I've also tried adding in as a parameter to the returned instance:
People(demo + (c.name, c))
But this keeps stating that (?,?) is required, pointing to c.name..
Any help is greatly appreciated
P.S. I'm looking to append to the set if the mapping already exists, not overwrite it
People(demo + (c.name, c))`But this keeps stating that (?,?) is required, pointing to c.name..
The problem is with the signature of the + method on Map, it requires a tuple of key and value, but the parentheses are "eaten" as method call parentheses. The following should work:
People(demo + ((c.name, c)))
or
People(demo + (c.name -> c))
But instead of c you will have to have the new set. So:
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With