score:1
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.
Source: stackoverflow.com
Related Query
- Is there any advantage to avoiding while loops in Scala?
- Scala extending while loops to do-until expressions
- Using Scala continuations with while loops
- Why are Scala for loops slower than logically identical while loops?
- Efficient way to fold list in scala, while avoiding allocations and vars
- Why are Scala for loops so much faster than while loops for processing a sequence of distinct objects?
- Scala: Any way to force a trait to return a certain type while permitting any arguments?
- Built-in way to simulate a while loop without side effects
- Why are while loops not recommended in scala
- While loops generated via Scala Macros are not equal
- Functional way to write while loop with mutable variable
- Is there any way to clear console output while using scala interpreter?
- Is there a way to navigate through library sources while using IntelliJ + Bazel + Scala?
- Making things immutable while working with loops in Scala
- Is there a way to override packageName in sbt while building dist?
- Extended scope in while loops scala
- Is there a way to chain `Try` as a monad while also not catching exceptions raised along the chain?
- Efficient way of using for loops in scala
- Best way to handle while loop style program in Scala
- specs2: Is there a way to use doNothing while mocking with Mockito?
- Is there a better way to pattern match and deconstruct my tuple, while discarding the rest?
- Scala - Alternative to nested for loops while writing out
- Scala's way of "while" loops
- Which will be the better way or more performance oriented while dealing with Maps in Scala
- How to write nested for loops in efficient way in scala?
- Best way to parse command-line parameters?
- ScalaTest in sbt: is there a way to run a single test without tags?
- Best way to merge two maps and sum the values of same key?
- Scala best way of turning a Collection into a Map-by-key?
- What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives?
More Query from same tag
- How to set a custom value to _id field while writing json document to Mongo DB using spark
- Runtime error on Scala Spark 2.0 code
- Correct way to handle make an external URL call in Scala play framework
- Re-using sessions in ScalaQuery?
- Akka RestartSource does not restart
- How to find the longest common prefix of two strings in Scala?
- What's Squeryl syntax for exclusion (i.e. != )?
- NullPointerException when referencing DataFrame column names with $ method call
- Does Fortify support Python, Scala, and Apache Spark?
- why is the lift web framework scalable?
- How to parse a json containing a field that always has a changed name in Scala?
- How do we send back the result of processed message by actor to the actual sender
- Scala Future with filter in for comprehension
- Better way of converting a Map[K, Option[V]] to a Map[K,V]
- Proper way for looping in Scala
- What was the reason to restrict on combining implicit parameters and view/context bounds?
- Spark SQL Group By Consecutive Sequence of Integers
- Creating two dimensional list and then making a DataFrame in Scala
- How to handle lifecycle signal with Behavior.receiveMessage
- Anatomy of Menu
- Writing to HBase via Spark: Task not serializable
- IntelliJ: breakpoints in Scala tests won't get hit
- Scala fasterxml jackson. Reading in a Yaml file, but the return data structure is difficult to work with
- combining scala mixing,self types and cascading method fails..is possible avoid it?
- Functional reposiotory - build get() based on find()/create() methods
- Scala - mapping to functions, struggling against contravariance
- Is there an elegant way in Ruby which acts like `require` in Scala?
- Play! framework: customize which tests are run
- Change sbt log tags: info,warn,success,error
- How to list annotations (custom java ones and others) on field members of Scala case class