Scala迭代器:“在调用方法之后永远不应该使用迭代器” – 为什么?

Iterator [T] here上的Scala文档说明如下:

It is of particular importance to note that,unless stated otherwise,one should never use an iterator after calling a method on it. The two most important exceptions are also the sole abstract methods: next and 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
}

不幸的是,我不遵循这里不安全的想法.有人能在这里为我揭开光明吗?

解决方法

val remainder = it.drop(2)可以这样实现:它创建一个新的包装器迭代器,它保持对原始操作符的引用并将其前进两次,以便下次调用remainder.next时获得第3个元素.但是如果你之间调用it.next,则remaining.next将返回第4个元素…

因此,您必须引用可能需要调用next的余数,并执行相同的副作用,这是实现不支持的.

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...