Wednesday, January 21, 2009

Scala example for accessing Ehcache Server

Back in December Greg Luck asked me to do a Scala example of accessing Ehcache, to fit in with the code samples on their site. Yesterday I finally got around to looking at it and Greg has now posted it on his blog.

My goal was not to write the perfect example. I decided to do something to fit in with the style of the existing Ruby code sample, which just prints the response of a HTTP GET to a fixed URL. Given that this is the sole purpose of the program, I didn't see the point of explicitly handling exceptions or closing network connections.

I couldn't find a HTTP client library written in Scala, so rewriting the Java code sample would basically be a thin veneer of Scala syntax over the Java libraries. Too much time for little value.

I must admit that I had the total number of lines of code in the back of my mind, simply because the other samples, apart from the Java one (which does more) are all short and people will notice this. Personally I think this emphasis on short LOC, considered in isolation is misguided.

For me, the expressiveness of a language is more important, i.e. the ability to express abstractions and properties that matter (or perhaps should matter). Assuming that it is possible to express a particular concept in a language, the next question is how easy it is to do so and LOC/number of characters are aspects of this.

Here is my simple Scala program:

import java.net.URL
import scala.io.Source.fromInputStream

object ExampleScalaGet extends Application {
val url = new URL("http://localhost:8080/ehcache/rest/sampleCache2/2")
fromInputStream(url.openStream).getLines.foreach(println)
}

I see three meaningful language features utilised (apart from static typing):
  • Easy definition of an immutable value. The keyword val on line 5.

  • Type inference. The type of the value url is not explicitly annotated in the code, but inferred at compile time.

  • Easy use of higher order functions. foreach on line 6, takes a function as its argument.

No comments: