type whereas map needs an instance of the same collection type constructor, but possibly with a different element type.
What’s more, even the result type constructor of a function like map might depend in non-trivial ways on the other argument types. Here is an example:
scala> import collection.immutable.BitSet import collection.immutable.BitSet
scala> val bits = BitSet(1, 2, 3)
bits: scala.collection.immutable.BitSet = BitSet(1, 2, 3)
scala> bits map (_ * 2)
res13: scala.collection.immutable.BitSet = BitSet(2, 4, 6)
scala> bits map (_.toFloat)
res14: scala.collection.immutable.Set[Float] = Set(1.0, 2.0, 3.0)
If you map the doubling function _ * 2 over a bit set you obtain another bit set. However, if you map the function (_.toFloat) over the same bit set, the result is a general Set[Float]. Of course, it can’t be a bit set because bit sets contain Ints, not Floats.
Note that map’s result type depends on the type of function that’s passed to it. If the result type of that function argument is again an Int, the result of map is a BitSet, but if the result type of the function argument is something else, the result of map is just a Set. You’ll find out soon how this typeflexibility is achieved in Scala.
The problem with BitSet is not an isolated case. Here are two more interactions with the interpreter that both map a function over a map:
scala> Map("a" -> 1, "b" -> 2) map { case (x, y) => (y, x) } res3: scala.collection.immutable.Map[Int,java.lang.String]
= Map(1 -> a, 2 -> b)
scala> Map("a" -> 1, "b" -> 2) map { case (x, y) => y } res4: scala.collection.immutable.Iterable[Int]
= List(1, 2)
The first function swaps two arguments of a key/value pair. The result of mapping this function is again a map, but now going in the other direction. In fact, the first expression yields the inverse of the original map, provided
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index