ps0604 ps0604 - 1 year ago 42
Scala Question

List of lists as Map value does not compile

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

Answer Source

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: as appending to list in scala has complexity of O(n)