Another tour of Scala


Scala Functions

The Gist

Anonymous Functions gives an overview of Scala’s support for functions as actual parts of the programming language. Higher-Order Functions explains how functions can take functions as arguments and also return functions.

My Interpretation

Scala is more than just an object-oriented language with a compact syntax; it has extensive support for functional programming. As such, functions are first-class objects.

Suppose you have a list of U.S. States and wish to search by postal abbreviation. In Java, you’d do something like this:

While this is reasonably clear, in Java you tend to write a lot of code like this, where you iterate over a list and “do something”. The main problem is that when you find out later you need to search by some other attribute, you write essentially the same looping and early-return structure.

Scala inverts this by allow you to pass in just the comparison function:

The expression given to the find method is a function literal, or anonymous function. The argument to the find method is declared to have the type (T) => Boolean, which is to say “A function that takes one argument of type ‘T’, where ‘T’ is the type of elements in the list, and returns a boolean.”

In our case, since the list is a list of State objects, the type of the function is (State) => Boolean, or “A function that takes one argument of type State and returns a Boolean.” Note that this entire expression is the type, the same as int or List<String> would be in Java. Also note that the expression (state) is a way in which we name the argument that would be passed to the function (Scala understands the type of this argument based on the context in which it is called).

That type is actually shorthand for Function1[State,Boolean], where the method apply is what is called when the function is called. The Scala compiler translates the shorthand for you.

Further, you can pass functions around just like variables and other values.

A few more interesting things about functions in Scala:

  • Methods of an object can be passed as functions
  • Methods and functions are not the same thing

Functions, their definitions, and their behavior are a very deep subject, but this should give you a flavor of what they can do. If you’ve done a lot of list manipulation (or Swing programming), you should be able to see that functions can save you from writing a ton of code…and result in much clearer code.

My Thoughts on this Feature

I dig this quite a bit. I could use this at work right now if it were available in Java. While many examples of Scala use functions in a way that really confuses things, I still think this feature has the power to simplify and clarify a lot of code. It is the logical continuation of the “inversion of control” concept; here, a class can ask for code it needs, instead of exporting its data.

Last Updated 08/22/2009 at 09:42:50 AM by davec

blog comments powered by Disqus