Concatenate TraversableOnce objects in Scala?

concatenation, iterator, scala

Solution

You can join iterators with ++. So if you're going to use iterators anyway, just

def ++(t2: TraversableOnce[T]): TraversableOnce[T] = t.toIterator ++ t2.toIterator

The reason to not do this is to supply an efficient `foreach` for `Traversable`s that are not `Iterable`/`Iterator`, but then you need to fill in all the `TraversableOnce` abstract methods.

Problem

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() } } ```

Original source