I want to concatenate a traversable once to a traversable once without resolving either.
This is the solution I have come up with as an implicit, but I don’t know if I am missing a native solution…
object ImplicitTraversableOnce {
implicit def extendTraversableOnce[T](t : TraversableOnce[T]) = new TraversableOnceExtension(t)
}
class TraversableOnceExtension[T <: Any](t : TraversableOnce[T]) {
def ++ (t2:TraversableOnce[T]):TraversableOnce[T] = new concat(t.toIterator, t2.toIterator)
private class concat(i1:Iterator[T], i2:Iterator[T]) extends Iterator[T] {
private var isOnSecond = false
def hasNext:Boolean =
if (isOnSecond) i2.hasNext
else if (!i1.hasNext) {
isOnSecond = true
hasNext
}
else true
def next():T = if (isOnSecond) i2.next() else i1.next()
}
}
You can join iterators with ++. So if you’re going to use iterators anyway, just
The reason to not do this is to supply an efficient
foreachforTraversables that are notIterable/Iterator, but then you need to fill in all theTraversableOnceabstract methods.