Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My experience with Scala is that there is more than one way to do things, but relatively few "best" ways to do things. The library has very few gratuitous options for doing things different ways; when it does so, it's usually to enable extra expressiveness or compactness or efficiency in a subset of cases.</p> <p>For example, if you want to sum an array of integers, you could be completely procedural, which would generate code that was as fast as possible, at the expense of being a little clunky--but if this is really time-critical code, this is the unique best way to solve the problem:</p> <pre><code>val array = Array(1,2,3,4,5) var sum = 0 var index = 0 while (index &lt; array.length) { sum += array(index) index += 1 } sum </code></pre> <p>There are equally general functional approaches that are slower when working with primitives (this may change with <a href="http://sites.google.com/site/scalatohoku/type-specialization-on-scala-2-8" rel="noreferrer">@specialized</a> in 2.8) but leave you with less tedium:</p> <pre><code>var sum = 0 Array(1,2,3,4,5).foreach(x =&gt; sum += x) sum </code></pre> <p>And then there are slightly less general functional constructs that are designed for just this sort of problem (since it comes up a lot) and this is "best" if you want clean, compact code:</p> <pre><code>Array(1,2,3,4,5).reduceLeft( _ + _ ) </code></pre> <p>And sometimes there are very non-general constructs to do exactly what you want; in Scala 2.8, for example:</p> <pre><code>Array(1,2,3,4,5).sum </code></pre> <p>So you get a continuum of choices with tradeoffs in general power, compactness, clarity, and speed. If you can assume that the code needs only to be accessible to people who are quite familiar with Scala, and you know whether you need the absolute best possible performance or not, the good choices are usually rather limited. But, because of the expressive power of the language and library, there are usually many possible if suboptimal ways to do things.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload