使用迭代器

时间:2018-04-03 15:36:17

标签: scala iterator main read-eval-print-loop

我对使用Scala的dropWhile谓词和迭代器有疑问。 这里我有一个简单的迭代器创建:

scala> val it = Iterator("a" , "number" , "of" , "words")
it: Iterator[String] = non-empty iterator

接下来我在其上使用dropWhile谓词:

scala> it dropWhile ( _.length < 2 )
res52: Iterator[String] = non-empty iterator

接下来,我在Iterator上执行下一个命令:

   scala> it next
   res53: String = of

现在注意迭代器下一个命令返回“of”,超过它应该是什么。

如果我将相同的代码放在main函数中,则下一个将返回“a”。 这相当令人困惑。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:4)

来自docs

  

特别重要的是要注意,除非另有说明,   在调用方法之后,永远不应该使用迭代器。他们俩   最重要的例外也是唯一的抽象方法:next和   hasNext。

您需要将dropWhile的结果分配给新变量并继续使用它。例如

val remaining  = it dropWhile ( _.length < 2 )
remaining.next

答案 1 :(得分:0)

Scala docsIterators解释为

  

An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it.next() will return the next element of the iterator and advance the state of the iterator. Calling next again on the same iterator will then yield the element one beyond the one returned previously. If there are no more elements to return, a call to next will throw a NoSuchElementException.

REPL

当你在REPL中应用it dropWhile ( _.length < 2 )时,它被分配到res52

  

scala> it dropWhile ( _.length < 2 ) res52: Iterator[String] = non-empty iterator

"a" , "number"已被访问。因此,应用it next会为您of提供 100%正确

主要

main(),您必须完成

val it = Iterator("a" , "number" , "of" , "words")
it dropWhile ( _.length < 2 )
print(it next)

您可以清楚地看到it dropWhile ( _.length < 2 )未在REPL中分配。因此,尚未访问 "a" , "number"

因此it nexta

中打印main()

我希望解释有用