【发布时间】:2013-08-24 17:03:15
【问题描述】:
Iterator[T] here 上的 Scala 文档说明如下:
特别重要的是要注意,除非另有说明,否则绝不应在调用迭代器方法后使用迭代器。两个最重要的例外也是唯一的抽象方法:
next和hasNext。
他们还给出了安全和不安全使用的具体示例:
def f[A](it: Iterator[A]) = {
if (it.hasNext) { // Safe to reuse "it" after "hasNext"
it.next // Safe to reuse "it" after "next"
val remainder = it.drop(2) // it is *not* safe to use "it" again after this line!
remainder.take(2) // it is *not* safe to use "remainder" after this line!
} else it
}
不幸的是,我在这里没有遵循不安全的想法。有人可以在这里为我解释一下吗?
【问题讨论】:
-
"重用:在调用 drop/take 方法后,应该丢弃它被调用的迭代器,并且只使用返回的迭代器。使用旧的迭代器是未定义的,可能会改变,并且可能也会导致对新迭代器的更改。”