Search code examples
scalabufferedreader

BufferedReader readLine return value not understood as string in scala?


Although I realize there are native scala ways to do the following, nevertheless it would be insightful to understand the behavior.

For the following code snippet the for loop iterator is not correct:

val br = new BufferedReader(new FileReader("/tmp/test.txt"))
val stdin = new FileOutputStream("/tmp/x.txt")
for (line : String <- br.readLine) {
  //    val mys = new String(line)
  stdin.write(line)
  stdin.write('\n')
}

The iterator line gives the following compilation error:

scrutinee is incompatible with pattern type;
 found   : String
 required: Char
    for (line : String <- br.readLine) {

            ^

Solution

  • br.readLine returns a String, the map operation on String works on Char

    for { line <- br.readLine }

    is same as

    br.readLine.map { line =>

    You may write it like this instead:

    val br = new BufferedReader(new FileReader("/tmp/test.txt"))
    val outfile = new FileOutputStream("/tmp/x.txt")
    
    var line:String = ""
    
    while ({ line = br.readLine() ; line != null } ) {
    
       outfile.write(line.getBytes)
       outfile.write('\n')
    }