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

An optional method is a method that can be applied if the generics class is of a particular type. examples:

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

Currently I want to implement a regression method that has the same limitations as unzip (i.e. collecting 2d points), but I don’t know how to make sure that the (implicit asPair: A => (A1, A2)exsist method is and where it is best to determine such transformations.

+5
source share
1 answer

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]
+10
source

All Articles