Scala 2.13 migration guide contains a note regarding how to port collection.breakOut
:
collection.breakOut
no longer exists, use.view
and.to(Collection)
instead.
and few paragraphs below in a overview table there is:
Description Old Code New Code Automatic Migration Rule collection.breakOut
no longer existsval xs: List[Int]
= ys.map(f)
(collection.breakOut)
val xs =
ys.iterator.map(f).to(List)
Collection213Upgrade
The scala-collection-migration
rewrite rule uses .iterator
. What is the difference between the two? Is there a reason to prefer one to the other?
When used like that there is no real difference.
A View
can be reused while an Iterator
must be discarded after it's been used once.
val list = List(1,2,3,4,5)
val view = list.view
val viewPlus1 = view.map(_ + 1).toList
view.foreach(println) // works as expected
val it = list.iterator
val itPlus1 = it.map(_ + 1).toList
it.foreach(println) // undefined behavior
In its simplest form a View[A]
is a wrapper around a function () => Iterator[A]
, so all its methods can create a fresh Iterator[A]
and delegate to the appropriate method on that iterator.