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
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.
How about:
def ++(t2: TraversableOnce[T]) = new Traversable[T] {
def foreach[U](f: (T) => U) {
t.foreach(f)
t2.foreach(f)
}
}
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