5

Optional method is method which can be applied if class generics has specific type. examples:

list.unzip //works only if this is collection of pairs
list.sum //works only if this collection of numbers

Currently I want implement regression method which has the same constraints as unzip(i.e. collection of 2d points) but I don't know how to make sure that method (implicit asPair: A => (A1, A2) exsist and where the best place to define such conversions.

yura
  • 14,489
  • 21
  • 77
  • 126
  • 4
    You might find [generalized type constraints](http://stackoverflow.com/questions/3427345/what-do-and-mean-in-scala-2-8-and-where-are-they-documented) useful. – Tom Crockett Apr 16 '12 at 19:08

1 Answers1

10

Here's what TraversableOnce.toMap does to ensure it is only called on a collection 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 are looking to add a similar method to an existing collection class, you can make it even easier:

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]
dhg
  • 52,383
  • 8
  • 123
  • 144