Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 非空迭代器在打印后变为空_Scala_Iterator - Fatal编程技术网

Scala 非空迭代器在打印后变为空

Scala 非空迭代器在打印后变为空,scala,iterator,Scala,Iterator,在scala中,我使用返回非空迭代器的getLines读取文件。然后我用for循环打印了这些行。之后,当我再次尝试打印时,它显示为空迭代器。有人能解释一下吗 scala> c res1: Iterator[String] = non-empty iterator scala> println(c) non-empty iterator scala> for ( line <- c) println(line) insert into songlist (id, ar

在scala中,我使用返回非空迭代器的getLines读取文件。然后我用for循环打印了这些行。之后,当我再次尝试打印时,它显示为空迭代器。有人能解释一下吗

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

这是迭代器的预期行为,因为当您不断遍历迭代器时,状态会发生变化。因此迭代器是可变的

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
阅读

特别重要的是要注意,除非另有说明, 在调用迭代器上的方法后,决不能使用迭代器

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

例如

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")
res8: Iterator[String] = non-empty iterator

scala> res8.foreach(println)
order1
order2
order3

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

特别重要的是要注意,除非另有说明, 在调用迭代器上的方法后,决不能使用迭代器

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

例如

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