Java BufferedReader, readLine, and a Scala while loop

I generally try to avoid this coding style these days, but, if you want to see how to use a Java BufferedReader and its readLine method in a Scala while loop, here you go:

@throws(classOf[IOException])
def readFileToStringArray(canonFilename: String): Array[String] = {
    val bufferedReader = new BufferedReader(new FileReader(canonFilename))
    val lines = new ArrayBuffer[String]()
    var line: String = null
    while ({line = bufferedReader.readLine; line != null}) {
        lines.add(line)
    }
    bufferedReader.close
    lines.toArray
}

For this example, these are the important lines to look at:

val lines = new ArrayBuffer[String]()
var line: String = null
while ({line = bufferedReader.readLine; line != null}) { 
    lines.add(line)
}

The most important part of that code — and the biggest difference from Java — is how you need to handle the readLine method inside the Scala while loop, specifically using it in a block of code that’s wrapped in curly braces, where that block of code returns a Boolean value. (The semi-colon inside that block of code helps me include two lines of Scala code inside the curly braces.)

I don’t have much time to explain this code tonight, so I hope it makes sense as is. In summary, if you wanted to see how to use a Java BufferedReader and its readLine method inside a Scala while loop, I hope this example is helpful.