= Solution
Use <iterator concatenation> and short-circuit the second availability test while the first <iterator> still has results:
``
class ConcatIterator[T](first: Iterator[T], second: Iterator[T])
extends Iterator[T] {
def hasNext: Boolean = first.hasNext || second.hasNext
def next(): T = {
if (first.hasNext) first.next()
else second.next()
}
}
``
The abstract remaining <sequence> is the remaining <sequence> of `first` followed by that of `second`. Each `next()` consumes the head of precisely this <sequence>. When both are exhausted, delegation to `second.next()` raises the required exception. \b[Construction consumes no elements], and `hasNext` never calls either underlying `next()`. As usual, clients should not separately consume these <iterators> while relying on the adapter's traversal. Sharing one underlying <iterator> between both arguments also shares its state; it does not duplicate its elements.
Back to article page