Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to define type safe optional methods in Scala?

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.

like image 986
yura Avatar asked Apr 16 '12 18:04

yura


1 Answers

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]
like image 122
dhg Avatar answered Sep 20 '22 16:09

dhg