Something I had been meaning to post for a while, was a simple snippet showing the use functions as values and/or variables in Scala and how expressive this is at conveying intent within the code.

Below is a snippet that I hacked together on the train home one evening after talking through the functional requirements of an authorization and data filtering module with a few guys from work. The snippet is pretty rough and ready, but I think it imparts the key elements of what we were trying to achieve.

Only minor points of note here are that it also uses inner methods, and I had wrapped the whole sample in an object (as opposed to just testing this out in the REPL), as I had developing this with sbt and the background task of run (using the ~run command to spool the file for changes and recompile and re-run the classes automatically). I was also running Scala 2.8.1 for my session (with the ++2.8.1 command once I’d entered the sbt environment.  Something to be aware of, is that sbt uses 2.7.7 for itself, so you will always see it pull down 2.7.7 first time around).

Hopefully the snippet is reasonably clear, and gives a good sense of when treating functions as member values and variables makes life a lot easier and intent a lot clearer.

Leave a Reply

You must be logged in to post a comment.