Scala迭代器:“在调用方法之后永远不应该使用迭代器” – 为什
发布时间:2020-12-16 09:50:02 所属栏目:安全 来源:网络整理
导读: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 method
Iterator [T]
here上的Scala文档说明如下:
他们还给出了安全和不安全使用的具体示例: 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的余数,并执行相同的副作用,这是实现不支持的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |