score:1

Accepted answer

a more idiomatic solution would be to use a tail-recursive method rather than a while loop. this will also be more efficient that using stream.continually:

@scala.annotation.tailrec
def readall: unit = {
  val n = rdr.read(buffer)
  if (n != -1) {
    stwr.write(buffer, 0, n)
    readall
  }
}
readall

internally, scala rewrites this as a while loop. what makes this more idiomatic than a while loop is that it allows us to use val rather than var in most places. for example, here n can be a val. more complex examples will have method parameters, these can fill the role of variables that are updated inside the loop.

score:1

it is slightly more idiomatic, they are not equivalent, but i believe that's by accident as there is a bug in your while loop (see below for correction). your scala style is a bit off though - your using infix notation too much in that line of code because it's got quite a lot of chaining, so you should stick to dot notation. also only use curly braces when you need to, otherwise use round braces. so

stream.continually(isr read buffer).takewhile(_ != -1)
.foreach(x => sw write (buffer, 0, x))

but when it comes to code that requires while-like behaviour due to the absence of a clear upper bound, it really isn't the end of the world if you use a while loop (a lot of the scala code itself uses while loops). the problem is the var, which should be avoided. nevertheless for optimized code, one sometimes must use var. so, again once we have corrected your style (and the bug) the while is ok also:

var n = isr read buffer
while (n != -1) {
  sw write (buffer, 0, n)
  n = isr read buffer
}

the bug was you read twice before writing. we could also fix it like this:

var n: int = _
while ({
  n = isr read buffer
  n != -1 
}) {
  sw write (buffer, 0, n)
}

one final point, i would actually use dot notation for read and write methods also, but it's a matter of taste so i've left it as infix. my argument is that i only use infix notation when the method is being use as though it should be an operator - but that's just my opinion.


Related Query

More Query from same tag