I'm looking at Scala 2.12 Collection Library sources and noticed the following thing:
trait TraversableOnce[+A] extends Any with GenTraversableOnce[A] {
//methods
implicit class MonadOps[+A](trav: TraversableOnce[A]) {
def map[B](f: A => B): TraversableOnce[B] = trav.toIterator map f
def flatMap[B](f: A => GenTraversableOnce[B]): TraversableOnce[B] = trav.toIterator flatMap f
def withFilter(p: A => Boolean) = trav.toIterator filter p
def filter(p: A => Boolean): TraversableOnce[A] = withFilter(p)
}
}
What is the reason the Monad Ops are put into implicit
class? The Traversable
subtrait of TraversableOnce
has this all monadic methods defined not as imlpicit class (through TraversableLike
though).
Iterator
, as something we only expect to traverse once, is an example of something that extends TraversableOnce
without extending Traversable
. The methods on MonadOps
will be used there.
Note MonadOps
is in the companion object, not the trait.
Also note TraversableOnce
has been deprecated in 2.13.0 in favour of IterableOnce
.