Scala中Iterator迭代器一个魔幻的地方
Scala中Iterator迭代器一个魔幻的地方
package mucao.com
import scala.io.Source import java.io.PrintWriter import scala.collection.mutable.ArrayBuffer
object test2 extends App {
val path = "test.txt" val source = Source.fromFile(path) val reader=source.getLines() val pattern="\t".r //注意:下一行代码生成的是一个迭代器,因为reader是迭代器,所以由for推导式生成的result也是一个迭代器 val result = for ( t <- reader) yield t.toString val temp_res=new Array[String](result.length)//在这里定义一个数组,长度是result的长度 result.foreach(println)
}
test.txt文档内容 zhg hello world
然后保存,运行程序得到的结果是什么都不打印
当把 val temp_res=new Array注释起来的时候 将会打印: zhg hello world
最后查到的原因是: 在调用result.length的时候,已经相当于把result迭代器调用了一遍了。result迭代器已经指向最后的位置了所以当再次调用result来打印输出语句时,什么都不会打印!
