Вопрос

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.

Это было полезно?

Решение

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].

Другие советы

The result is AFAIK an Iterator[String], so I'm not sure why I can only iterate on it once.

Because this is how Iterators 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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top