Following on from another question I asked, Scala 2.8 breakout, I wanted to understand a bit more about the Scala method TraversableLike[A].map
whose signature is as follows:
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
Notice a few things about this method:
- It takes a function turning each
A
in the traversable into aB
. - It returns
That
and takes an implicit argument of typeCanBuildFrom[Repr, B, That]
.
I can call this as follows:
> val s: Set[Int] = List("Paris", "London").map(_.length)
s: Set[Int] Set(5,6)
What I cannot quite grasp is how the fact that That
is bound to B
(that is, it is some collection of B's) is being enforced by the compiler. The type parameters look to be independent of both the signature above and of the signature of the trait CanBuildFrom
itself:
trait CanBuildFrom[-From, -Elem, +To]
How is the Scala compiler ensuring that That
cannot be forced into something which does not make sense?
> val s: Set[String] = List("Paris", "London").map(_.length) //will not compile
How does the compiler decide what implicit CanBuildFrom
objects are in scope for the call?