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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With