scala 2.8 CanBuildFrom
Posted
by
oxbow_lakes
on Stack Overflow
See other posts from Stack Overflow
or by oxbow_lakes
Published on 2009-11-12T10:38:22Z
Indexed on
2012/06/03
22:40 UTC
Read the original article
Hit count: 151
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?
© Stack Overflow or respective owner