Skip to content

Commit e7d593d

Browse files
committed
Fix unreported bug in View.Patched
Fix unreported bug in `View.Patched` where iterator is incorrect due to the patch only being iterable once, and already having been exhausted. Discovered while attempting to optimise `ArrayBuffer` in an earlier version of the previous commit.
1 parent d50a7a5 commit e7d593d

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

library/src/scala/collection/View.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,8 +404,14 @@ object View extends IterableFactory[View] {
404404

405405
@SerialVersionUID(3L)
406406
private[collection] class Patched[A](underlying: SomeIterableOps[A], from: Int, other: IterableOnce[A], replaced: Int) extends AbstractView[A] {
407-
def iterator: Iterator[A] = underlying.iterator.patch(from, other.iterator, replaced)
408-
override def knownSize: Int = if (underlying.knownSize == 0 && other.knownSize == 0) 0 else super.knownSize
407+
// we may be unable to traverse `other` more than once, so we need to cache it if that's the case
408+
private val _other: Iterable[A] = other match {
409+
case other: Iterable[A] => other
410+
case other => LazyList.from(other)
411+
}
412+
413+
def iterator: Iterator[A] = underlying.iterator.patch(from, _other.iterator, replaced)
414+
override def knownSize: Int = if (underlying.knownSize == 0 && _other.knownSize == 0) 0 else super.knownSize
409415
override def isEmpty: Boolean = if (knownSize == 0) true else iterator.isEmpty
410416
}
411417

0 commit comments

Comments
 (0)