微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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的余数,并执行相同的副作用,这是实现不支持的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐