When first starting out with Scala after programming in Java for many years chances are you are still writing Java code just in Scala syntax. Meaning you are not leveraging all the functional goodness that is Scala. Functional code is usually more concise and can be more expressive than imperative code, because functional language constructs operate on a higher level of abstraction than your ordinary execution path loop and fork. It is more about saying what you want and less about how you want it done.
I found the following actions helpful in my quest to make my Scala code less imperative and more functional:
- Try to eliminate variables and loops by replacing them with list comprehensions and recursion.
- Try to eliminate if statements by replacing them with pattern matching.
Basically, I look for the key words ‘var’, ‘for’, ‘while’ and ‘if’ in my code and try to think up a way to replace them with something more functional. The result is usually not obvious (for non-(not yet)-functional programmers that is anyway), but I tend to like it more than what I had before.