打印后非空Iterator变空

时间:2017-12-11 02:51:09

标签: scala iterator

在scala中,我使用getLines读取了一个文件,该文件返回了一个非空的Iterator。然后我用for循环打印了这些线条。之后,当我再次尝试打印时,它说空Iterator。有人可以解释一下吗?

scala> c
res1: Iterator[String] = non-empty iterator

scala> println(c)
non-empty iterator

scala> for ( line <- c) println(line)

insert into songlist (id, artist, title, numone) values (1, 'ABBA', 'WATERLOO', 0);
insert into songlist (id, artist, title, numone) values (2, 'ABBA',.............

scala> var d = for ( line <- c) println(line)
d: Unit = ()
scala> c
res8: Iterator[String] = empty iterator

1 个答案:

答案 0 :(得分:4)

Iterator这是非常期待的行为,因为当你继续遍历Iterator状态变化时。 (因此Iterator是可变的)

scala> Iterator("order1", "order2", "order3")
res8: Iterator[String] = non-empty iterator

scala> res8.foreach(println)
order1
order2
order3

scala> res8
res10: Iterator[String] = empty iterator

阅读Iterator docs

  

特别重要的是要注意,除非另有说明,   在调用方法之后,永远不应该使用迭代器。

如果要多次迭代,请转换为不可变的数据结构,如列表或序列。

例如,

scala> Iterator("order1", "order2", "order3", "order4")
res18: Iterator[String] = non-empty iterator

scala> res18.toList
res19: List[String] = List(order1, order2, order3, order4)

scala> res19.foreach(println)
order1
order2
order3
order4

scala> res19.foreach(println)
order1
order2
order3
order4

toSeq

scala> Iterator("order1", "order2", "order3", "order4")
res23: Iterator[String] = non-empty iterator

scala> res23.toSeq
res24: Seq[String] = Stream(order1, ?)

scala> res24.foreach(println)
order1
order2
order3
order4

scala> res24.foreach(println)
order1
order2
order3
order4