文件I / O循环过早破坏?

时间:2012-02-04 21:05:56

标签: scala for-loop

我正在使用此循环逐行读取文件:

for(line <- s.getLines()){
  mylist += otherFunction(line);
}

其中变量mylistArrayBuffer,它存储自定义数据类型的集合。 otherFunction(line);做了类似的事情......

def otherFunction(list:String)={
  val line = s.getLine(index);
  val t = new CustomType(0,1,line(0));
  t
}

CustomType定义为......

class CustomType(name:String,id:Int,num:Int){}

我已经省略了大部分代码,因为它不相关。我可以运行其余的函数,只要我注释掉otherFunction()的最后一行,它就会逐行读取文件直到EOF。为什么在这个函数中返回一个值到我的列表导致我的for循环停止?

1 个答案:

答案 0 :(得分:2)

目前尚不清楚你到底想要做什么。我假设sscala.io.Source个对象。为什么otherFunction采用不使用的字符串参数? getLine已被弃用,您没有说index来自何处。你真的想引用索引为0的行String中的第一个字符,它真的应该是Int吗?假设这实际上是你想要做的,为什么不在迭代器上使用map

val list = s.getLines.map(i => new CustomType("0", 1, i(0).asDigit)).toIndexedSeq