0

I have in Scala a Map where the values are list of lists. I try to add a value with the following code:

var map = Map[String,List[List[String]]]()
val list1 = List ("A111", "B111")
var listInMap = map.getOrElse("abc", List[List[String]]())
listInMap += list1   // this line does not compile
map += ("abc" -> listInMap)

The problem is that in the line listInMap += list1 it throws type mismatch; found : List[String] required: String. Why is String required if I need to add a list to the list? I need to add list1 to listInMap

ps0604
  • 1,227
  • 23
  • 133
  • 330

2 Answers2

5

listInMap += list1 is equivalent to listInMap = listInMap + list1. + operator is not defined in List for latest scala library (2.11.8) (marked deprecated in 2.7). So, + operator just concat the string values of listInMap and list1 with latest scala library.

For latest scala, you can use, listInMap = listInMap :+ list1

Also, check this: https://stackoverflow.com/a/7794297/1433665 as appending to list in scala has complexity of O(n)

Community
  • 1
  • 1
TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
1

Your problem is that list1 is not being inserted at the correct depth/level.

This will compile.

. . .
map += ("abc" -> (listInMap ++ List(list1)))
map("abc")  // result: List[List[String]] = List(List(A111, B111))
jwvh
  • 50,871
  • 7
  • 38
  • 64