Why can't directly add tuple2 to a map

I’am leaning the scala programming 3rd .chapter 3 use set and map.
the code on the book said the ( a → b) just convert to (a,b) ,then i read the source code ,that’s true
however the fallowing code can’t be complied

    val treasureMap = mutable.Map[Int, String]()
    treasureMap += ( 1 -> "GO to island")
    treasureMap += (2 -> "find big x on Ground")
    treasureMap += (3 -> "dig")
    //error ,replace with tuple
    treasureMap += (4,"haha you find nothing")
    treasureMap.foreach(println(_))

error info:

type mismatch;
found : Int(4)
required: (Int, String)
treasureMap += (4,“haha you find nothing”)

can anybody tell me why?thanks a lot

Because += (foo, bar) is not adding a tuple, but calling a method of two arguments; sadly they look the same.

1 Like

thanks a lot

In both cases you need a pair of parens around the full single argument. a -> b desugars to (a, b), so this should work:

treasureMap += ((4,"haha you find nothing"))
1 Like

nice , it works

Note that I would normally instead write:

treasureMap(1) = "GO to island"

the other way is fine too, but this way seems more readable to me.

2 Likes