How does Scala's mutable Map update [map(key) = newValue] syntax work?

后端 未结 3 907
温柔的废话
温柔的废话 2020-12-15 17:46

I\'m working through Cay Horstmann\'s Scala for the Impatient book where I came across this way of updating a mutable map.

scala> val scores = scala.coll         


        
相关标签:
3条回答
  • 2020-12-15 18:21

    Can you try this: => to update list of Map

    import java.util.concurrent.ConcurrentHashMap
    import scala.collection.JavaConverters._
    import scala.collection.concurrent
    
    val map: concurrent.Map[String, List[String]] = new ConcurrentHashMap[String, List[String]].asScala
    
    def updateMap(key: String, map: concurrent.Map[String, List[String]], value: String): Unit = {
    map.get(key) match {
    case Some(list: List[String]) => {
    val new_list = value :: list
    map.put(key, new_list)
    }
    case None => map += (key -> List(value))
    }
    }
    
    0 讨论(0)
  • 2020-12-15 18:24

    The problem is you're trying to update immutable map. I had the same error message when my map was declared as

    var m = new java.util.HashMap[String, Int]
    

    But when i replaced the definition by

    var m = new scala.collection.mutable.HashMap[String, Int]
    

    the m.update worked.

    0 讨论(0)
  • 2020-12-15 18:29

    This is an example of the apply, update syntax.

    When you call map("Something") this calls map.apply("Something") which in turn calls get.

    When you call map("Something") = "SomethingElse" this calls map.update("Something", "SomethingElse") which in turn calls put.

    Take a look at this for a fuller explanation.

    0 讨论(0)
提交回复
热议问题