简体   繁体   中英

Is there *any* difference between map.updated(k,v) and map + (k,v)? I'm getting a compile error on one but not the other

I'm new (about a month) to Scala. I just came across a type-check error that I can't figure out

This snippet works as expected.

  def combine(m: Map[Char, Int], tup: (Char, Int)): Map[Char,Int] = tup match {
    case (key: Char, value: Int) => m updated (key, m.getOrElse(key, 0) + value)
  }

This snippet gives a type mismatch error on value

  def combine(m: Map[Char, Int], tup: (Char, Int)): Map[Char,Int] = tup match {
    case (key: Char, value: Int) => m + (key -> m.getOrElse(key, 0) + value)
  }

 found   : Int
 required: String
           case (key: Char, value: Int) => m + (key -> m.getOrElse(key, 0) + value)
                                                                             ^

Now, the docs on map say that ms updated (k,v) is equivalent to ms + (k->v) but that appears to not be the case.

Here's my setup:

SBT version 0.13.8
Scala version 2.11.8
Java SDK 1.8
IntlliJ IDEa

key -> m.getOrElse(key, 0) + value means, (key->m.getOrElse(key, 0)) + value . So, effectively, you are trying to add an Int to a tuple, no surprise, that does not work.

Try using parentheses: m + (key -> (m.getOrElse(key, 0) + value))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM