I saw a Scala method recently that was written like this:
def abs (i: Int): Int = { if (i < 0) -i else i }
There’s nothing wrong with this method, especially if you’re new to Scala. The method does one thing, and it’s very readable. However, it’s important to know that you can do a number of things to simplify the method, and by the time you’re done with the simplifications it will be easier to read.
The return type isn’t necessary
First, in cases like this where the return type is obvious, you can remove it:
def abs (i: Int) = { // return type removed if (i < 0) -i else i }
The curly braces aren’t necessary
Next, because an if
/then
expression returns a result, it can be used just like a Java ternary operator. Along with the flexibility of Scala’s syntax, this lets you remove the curly brackets from around the method body, and write the method as a one-liner:
def abs (i: Int) = if (i < 0) -i else i
This is one of the many things I love above Scala: If you keep breaking your methods down so they do only one thing (and only one thing), they can often end up as simple one-liners; the flexibility of the language lets that happen. Very importantly, the resulting code still remains readable.
So, if you’re new to Scala, take a look at your methods and functions, make sure they do one thing (and only one thing), and look at how the Scala syntax lets them be simplified.
About that abs method
The first method shown above was in a book. If you really need to get the absolute value of an integer in Scala, use the abs
method on an Int
, as shown in these REPL examples:
scala> 5.abs res0: Int = 5 scala> -5.abs res1: Int = 5