简体   繁体   English

为什么在迭代器上执行映射不会导致对其进行修改?

[英]Why does performing a map on an iterator not cause it to be modified?

> val textIt = text.split("\\s").iterator
> val upperIt = textIt.map(_.toUpperCase)
> textIt
res14: Iterator[String] = non-empty iterator

Why is textIt not empty? 为什么textIt不为空? I would expect it to become an empty iterator due to map iterating over them. 我希望由于map迭代它们而成为空迭代器。 What is actually happening under the hood? 实际情况是什么?

Method Iterator.map returns new Iterator object without traversing over it: 方法Iterator.map返回新的Iterator对象,而不遍历该对象:

def map[B](f: A => B): Iterator[B] = new AbstractIterator[B] {
  def hasNext = self.hasNext
  def next() = f(self.next())
}

Iterating over textIt is performed when you iterate over upperIt . textIt进行迭代是在对textIt进行迭代时upperIt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM