更新时间:2023-01-23 15:44:05
cleaned
是一个迭代器.
scala> val cleaned = lines.filter(_!="")
cleaned: Iterator[String] = non-empty iterator
在赋值之后它是非空的.scala 中的迭代器是一次性的——一旦你遍历它(例如通过应用 length
方法)它就变成空的:
Right after assigning it is non-empty. Iterators in scala are single-used - once you traversed it (e.g. by applying length
method) it becomes empty:
scala> cleaned.length
res0: Int = 13
scala> cleaned.length
res1: Int = 0
您可以通过转换为 List 或 Seq(懒惰)来修复该行为:
You can fix that behavior by converting to List, or to Seq (lazy):
scala> val lines=Source.fromFile("bla.txt").getLines
lines: Iterator[String] = non-empty iterator
scala> val cleaned = lines.filter(_!="").toSeq
cleaned: Seq[String] = Stream(first, ?)
scala> cleaned.length
res4: Int = 13
scala> cleaned.length
res5: Int = 13