Another tour of Scala

 
 
 
 

Scala Functions

Viewing old version f79e0ee27d7d41c4f845cefe84464ee05c16529c; View Current

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 (A) => Boolean, which is to say “A function that takes one argument, which has the type the same as the type of the list’s elements, and returns a boolean.”

In our case, since the list is a list of State objects, the type of the function is (State) => Boolean. Not that this entire expression is the type, the same as int or List<String> would be in Java.

That type is actually shorthand for Function2[State,Boolean], where the method apply 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.


Last Updated 07/23/2009 at 08:04:24 PM by davec

blog comments powered by Disqus