————————————————————————— Code: ————————————————————————— val pair = (99, "Luftballons") // pair is a tuple, can be created like this.
import scala.collection.mutable.Map val treasureMap = Map[Int, String]() treasureMap += (1 -> "Go to island.") treasureMap += (2 -> "Find big X on ground.") treasureMap += (3 -> "Dig.") // -> is a method to return a two-element tuple // += needs a param of two-element tuple
treasureMap += (99 , "Luftballons") // (99, "Luftballons") is a tuple, am I wrong?
———————————————————————— Compile out: ———————————————————————— error: type mismatch; found : Int(99) required: (Int, String) treasureMap += (99 , "Luftballons") ^ one error found
———————————————————————— Statement ———————————————————————— (99 , "Luftballons") is not a tuple, right ? but pair is a tuple. So pair can be add to the map by using "+=" method. So (99 , "Luftballons") needs a "=" method to do type casting, right? Why this conversion can not be automatic?
New to Scala, found this question, troubled me :( help me plz
What a surprise to me is that I add a pair of brackets and then it got through. ———————————————————————————— The code is here: ———————————————————————————— val pair = (99, "Luftballons") // pair is a tuple, can be created like this.
import scala.collection.mutable.Map val treasureMap = Map[Int, String]() treasureMap += (1 -> "Go to island.") treasureMap += (2 -> "Find big X on ground.") treasureMap += (3 -> "Dig.") // -> is a method to return a two-element tuple // += needs a param of two-element tuple
treasureMap += ((99 , "Luftballons")) // Pay attention to the brackets outer (99,"Luftballons"). // Goes right. But how to explain?
———————————————————————————— Statement: ———————————————————————————— Well, I finally understand. When I tried to use println((99, "Luftballons")) for test. I realised the pair of outer brackets is the one of left method. As println(...) needs a (), += needs the same. But why does this happen? treasureMap += 3 -> "Dig." // with no brackets at all and it goes well I think this is an syntactic sugar. The brackets are saved because of method +=. But when it is added, first default recognised as the part of method +=. So when we want to cast the 99,"..." to be a tuple, we must add another pair brackets.