Reputation: 21562
I can only seem to iterate over the result val once. Calling length iterates over it, and therefore calling result.next
causes an exception.
val result = for ( regex(name) <- regex findAllIn output) yield name
println(result.length)
println(result.next)
The result is AFAIK an Iterator[String], so I'm not sure why I can only iterate on it once.
Upvotes: 0
Views: 161
Reputation: 116266
The result is AFAIK an Iterator[String], so I'm not sure why I can only iterate on it once.
Because this is how Iterator
s work. You can't walk back or reset them - once you have iterated through them, they are "used up".
A workaround is to convert the result into e.g. a List
, which has no such limitations:
val result = (for ( regex(name) <- regex findAllIn output) yield name).toList
println(result.length)
println(result.head)
Upvotes: 2
Reputation: 7320
You can try calling something like toVector
on it so it stores it in a persistent collection, then you can iterate over it as many times as you like.
Iterator
will only let you traverse over the contents once, hence if you want to traverse it more than one time then turn it into a collection. Given that you have an Iterator[String]
, calling something like .toVector
on it will give you a Vector[String]
.
Upvotes: 2