Following on from another question I asked, 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
(i.e. it is some collection of B's) is being enforced by the compiler. The type parameters look to be independent in both the signature above and in 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
EDIT - this question of course boils down to: How does the compiler decide what implicit CanBuildFrom
objects are in scope for the call?