我正在使用此循环逐行读取文件:
for(line <- s.getLines()){
mylist += otherFunction(line);
}
其中变量mylist
是ArrayBuffer
,它存储自定义数据类型的集合。 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循环停止?
答案 0 :(得分:2)
目前尚不清楚你到底想要做什么。我假设s
是scala.io.Source
个对象。为什么otherFunction
采用不使用的字符串参数? getLine
已被弃用,您没有说index
来自何处。你真的想引用索引为0的行String中的第一个字符,它真的应该是Int
吗?假设这实际上是你想要做的,为什么不在迭代器上使用map
?
val list = s.getLines.map(i => new CustomType("0", 1, i(0).asDigit)).toIndexedSeq