Shane Kinsella
Shane Kinsella

Reputation: 267

null check in while loop in Scala, unusual behaviour

I am aggregating the contents of an InputStream using a BufferedReader using the form

while( (str = br.readLine()) != null){
  sb.append(str)
}

but this quickly caused an OutOfMemoryError as the null check failed to pick up the null and my StringBuffer keeps increasing in size...

I have verified that str does have a value of null and also verified that it is not "null".

Refactoring my code to

str = br.readLine()
while(str != null){
  sb.append(str)
  str = br.readLine()
}

works but I've no idea how this would be any different. Any ideas?

Upvotes: 1

Views: 1260

Answers (2)

Aamir
Aamir

Reputation: 2424

Archeg has explained it beautifully so try this :

var str = ""
while({str = br.readLine; str != null}) {

}

and since you are working in Scala, try using

scala.io.Source.fromInputStream(is).getLines().mkString("\n")

or

 val bufferedReader = new BufferedReader(inputStreamReader)
 Iterator continually bufferedReader.readLine takeWhile (_ != null) mkString

Upvotes: 1

Archeg
Archeg

Reputation: 8462

In scala the expression str = br.readline() yield return value of type Unit, which is always not equal to null. It should have given you a warning about comparing Unit to null.

You are correct to refactor it like that.

P.S. As @Jesper correctly commented your question, this is not the way you usually read a file in scala. So if you do that - please use his code example. If you have any other InputStream, you can use Source.fromInputStream

Upvotes: 4

Related Questions