简体   繁体   中英

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(ie 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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM