def average(x: List[Int]) : Float = x.foldLeft(0)(_ + _) / x.length.toFloat
UPDATE: while I was trying to show how iterative code can be turned into a functional expression, @soc rightly commented on an even shorter version of x.sum / x.length.toFloat
Usually I find that in Scala I need less to "go back in the middle." In addition, a large function is divided into smaller expressions that are clearer to reason. Therefore, instead of
var x = ... if (some condition) x = ... else x = ...
I would write if (some condition) ... otherwise ....
A similar thing happens with matching expressions. And you can always have helper nested classes.
As soon as you are comfortable with many forms of expressions that evaluate the result (for example, "if") without a return statement, the presence of one of your methods looks inappropriate.
In one place of work, we had a rule not to have a βreturnβ in the middle of the method, since it is easy for the reader of your code to skip it. If "return" is only on the last line, what's the point of having it at all?
source share