How to make your Scala code less imperative and more functional

Atlantis StartWhen 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.

About these ads

One thought on “How to make your Scala code less imperative and more functional

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s