Here, what TraversableOnce.toMapdoes to make sure that it is called only from a set of pairs.
def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
val b = immutable.Map.newBuilder[T, U]
for (x <- self)
b += x
b.result
}
But if you want to add a similar method to an existing collection class, you can make it even simpler:
class EnhancedIterable[T,U](x: Iterable[(T,U)]) { // CanBuildFrom omitted for brevity
def swapAll() = x.map(_.swap)
}
implicit def enhanceIterable[T,U](x: Iterable[(T,U)]) = new EnhancedIterable(x)
List((1,2), (3,4), (5,6)).swapAll // List((2,1), (4,3), (6,5))
List(1, 2, 3).swapAll // error: value swapAll is not a member of List[Int]
source
share