【问题标题】:dropWhile creates two iterators that have same underlying iterator?dropWhile 创建两个具有相同底层迭代器的迭代器?
【发布时间】:2017-05-11 17:38:54
【问题描述】:

我正在观察,一种我不完全理解的行为:

scala> val a = Iterator(1,2,3,4,5)
a: Iterator[Int] = non-empty iterator

scala> val b = a.dropWhile(_ < 3)
b: Iterator[Int] = non-empty iterator

scala> b.next
res9: Int = 3

scala> b.next
res10: Int = 4

scala> a.next
res11: Int = 5

它看起来像:迭代器a 的迭代器部分(1,2,3) 被消耗,而(4,5) 被留下。由于必须评估3,因此必须使用它,但根据dropWhile 的定义,必须包含在b 中。迭代器b3, (4,5),其中(4,5)a 的剩余部分,完全相同的迭代器。我的理解正确吗?

鉴于上述情况,它看起来很危险,b 的行为会通过对a 应用操作而改变。基本上我们有两个对象指向同一个位置。使用dropWhile 是不是像这种糟糕的风格?

【问题讨论】:

    标签: scala iterator


    【解决方案1】:

    来自documentation for Iterator

    特别重要的是要注意,除非另有说明,否则绝不应在调用迭代器方法后使用迭代器。两个最重要的例外也是唯一的抽象方法:nexthasNext

    基本上,一旦您在迭代器上调用任何方法,除了 nexthasNext,您应该认为它已被销毁,并丢弃它。

    【讨论】:

    【解决方案2】:

    使用dropWhile 是不是像这种糟糕的风格?

    是的:-)

    【讨论】:

    • 使用dropWhile 的风格一点也不差。之后它正在使用原始迭代器,这就是问题所在。
    • 你说得对,问题不在于dropWhile
    猜你喜欢
    • 2020-11-28
    • 2018-09-13
    • 2016-07-24
    • 2021-10-15
    • 2014-08-07
    • 1970-01-01
    • 2018-05-20
    • 2019-01-13
    • 2012-11-20
    相关资源
    最近更新 更多