问题
If I had two iterators I could just write iter1 ++ iter2
and iterators would not be computed until they are needed. Is there any way to chain Iterable
instances in the same way?
I tried to use iterable1 ++ iterable2
but it causes immediately calculating nested values just like they are added to some structure. Is it possible to avoid this extra calculations and creating extra data structures?
回答1:
No. Iterable
is just an interface that can be implemented by anything that can be iterated over. So when you have an Iterable[Int]
that can be either a lazy or a strict collection, there's no way to know.
scala> val iterable1: Iterable[Int] = List(1,2,3)
iterable1: Iterable[Int] = List(1, 2, 3)
scala> iterable1 ++ iterable1
res2: Iterable[Int] = List(1, 2, 3, 1, 2, 3)
scala> val iterable2: Iterable[Int] = List(1,2,3).view
iterable2: Iterable[Int] = SeqView(...)
scala> iterable2 ++ iterable2
res3: Iterable[Int] = SeqViewA(...)
回答2:
You can code a simple chain-iterable that is a lazy concatenation of Iterable:
case class Chain[A](iter: Iterable[A]*) extends Iterable[A]{
def iterator: Iterator[A] = iter.map(_.iterator).foldLeft(Iterator.empty: Iterator[A])(_++_)
}
Chain(List(1,2,3), 10 to 15, Vector(42,13))
来源:https://stackoverflow.com/questions/42650334/how-to-chain-iterable-without-computing-underlying-iterators