|
View:
New views
3 Messages
—
Rating Filter:
Alert me
|
|
|
Tuple2 and mapsI've been reading the scala eBook and found an example of adding a key value pair to a map:
map += (1 -> "Some String") it seems that the (1 -> "Some String") results in a Tuple2, however the (1, "Some String") also results in a Tuple2, as follows: scala> 1 -> "Some String" res8: (Int, java.lang.String) = (1,Some String) scala> res8 getClass res10: java.lang.Class[_] = class scala.Tuple2 scala> (1, "Some String") res11: (Int, java.lang.String) = (1,Some String) scala> res11 getClass res12: java.lang.Class[_] = class scala.Tuple2 The problem I have is understanding why map += (1 -> "Some String") works fine, but: scala> map += (1, "Some String") <console>:6: error: type mismatch; found : Int(1) required: (Int, String) map += (1, "Some String") ^ gives me an error. Thanks Lorenz |
|
|
Re: Tuple2 and mapsmap += foo is shorthand for:
map.+=(foo) Thus, map += (1, "Some String") is an attempt to call: map.+=(1, "Some String") map has no method that accepts an Int and a String, though it does have a method that accepts a tuple of Int and String. Yes, it's sad that the two mechanisms are not interchangeable. 2008/10/8 Lorenz Bateman <lorenzb@...>: > I've been reading the scala eBook and found an example of adding a key value > pair to a map: > > map += (1 -> "Some String") > > it seems that the (1 -> "Some String") results in a Tuple2, however the (1, > "Some String") also results in a Tuple2, as follows: > > scala> 1 -> "Some String" > res8: (Int, java.lang.String) = (1,Some String) > > scala> res8 getClass > res10: java.lang.Class[_] = class scala.Tuple2 > > scala> (1, "Some String") > res11: (Int, java.lang.String) = (1,Some String) > > scala> res11 getClass > res12: java.lang.Class[_] = class scala.Tuple2 > > The problem I have is understanding why map += (1 -> "Some String") works > fine, but: > > scala> map += (1, "Some String") > <console>:6: error: type mismatch; > found : Int(1) > required: (Int, String) > map += (1, "Some String") > ^ > > gives me an error. > > Thanks > > Lorenz > |
|
|
Re: Tuple2 and mapsLorenz Bateman schrieb:
> The problem I have is understanding why map += (1 -> "Some String") > works fine, but: > scala> map += (1, "Some String") > gives me an error. Sometimes scala is a bit too clever in its handling of parens and you just have to add another pair, in this case to disambiguate between these two methods: def += (kv1 : (A, B), kv2 : (A, B), kvs : (A, B)*) : Unit Add two or more key/value pairs to this map. (The one you called) def += (kv : (A, B)) : Unit Add a key/value pair to this map. (The one you thought you called) Related: http://www.nabble.com/-scala--Parenthesis-inference-td19535942.html https://lampsvn.epfl.ch/trac/scala/ticket/1337 - Florian |
| Free embeddable forum powered by Nabble | Forum Help |