user1189870
user1189870

Reputation: 21

File I/O loop breaking prematurely?

I'm reading a file line by line using this loop:

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

where the variable mylist is a ArrayBuffer which stores a collection of custom datatypes. The otherFunction(line); does something like this...

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

and CustomType is defined as...

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

I've ommitted much of the code as you can see because it's not relevant. I can run the rest of my functions and it'll read the file line by line till EOF as long as I comment out the last line of otherFunction(). Why is returning a value in this function to my list causing my for loop to stop?

Upvotes: 0

Views: 122

Answers (1)

Luigi Plinge
Luigi Plinge

Reputation: 51109

It's not clear exactly what you're trying to do here. I assume s is a scala.io.Source object. Why does otherFunction take a string argument that it doesn't use? getLine is deprecated, and you don't say where index comes from. Do you really want to refer to the first character in the line String with index 0, and is it really supposed to be an Int? Assuming that this is actually what you want to do, why not just use a map on the iterator?

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

Upvotes: 2

Related Questions