Want Ruby-esque features on the JVM (or CLR)? Introducing Scala

Recently, while cruising the Internet (and, in particular, the Lambda-the-Ultimate site), I ran across the Scala programming language, latest brainchild of Martin Odersky (of GJ fame, which of course was derived from Pizza, among others). It's another entry in the hybrid functional/object language space, and as such, has a lot of interesting features that Ruby holds, but runs on the JVM (and can actually cross-compile into a .NET assembly, though it does require some slightly different mappings), and as such means developers don't have to make a wholesale commitment to the Ruby interpreter.

I thought I'd share some of the more interesting bits of Scala in this and a few more blog posts.

The high-level stuff

First of all, from the Scala website, let’s get the high-level overview stuff out of the way:

  • Scala is object-oriented. Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits. Class abstractions are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.
  • Scala is functional. Scala is also a functional language in the sense that every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. Scala’s case classes and its built-in support for pattern matching model algebraic types used in many functional programming languages. Furthermore, Scala’s notion of pattern matching naturally extends to the processing of XML data with the help of regular expression patterns. In this context, sequence comprehensions are useful for formulating queries. These features make Scala ideal for developing applications like web services.
  • Scala is statically typed. Scala is equipped with an expressive type system that enforces statically that abstractions are used in a safe and coherent manner. In particular, the type system supports generic classes, variance annotations, upper and lower type bounds, inner classes and abstract types as object members, compound types, explicitly typed self references, views and polymorphic methods. A local type inference mechanism takes care that the user is not required to annotate the program with redundant type information. In combination, these features provide a powerful basis for the safe reuse of programming abstractions and for the type-safe extension of software.
  • Scala is extensible. The design of Scala acknowledges the fact that in practice, the development of domain-specific applications often requires domain-specific language extensions. Scala provides a unique combination of language mechanisms that make it easy to smoothly add new language constructs in form of libraries: any method may be used as an infix or postfix operator, and closures are constructed automatically depending on the expected type (target typing). A joint use of both features facilitiates the definition of new statements without extending the syntax and without using macro-like meta-programming facilities.
I’ll be the first to admit, a lot of these features are new to me, but the set as a whole is impressive, even more so because they all seem to derive from some core features inherent to functional languages, and the overall impression I get is that despite the language feature set, it doesn’t feel “cluttered” or “clumsy”, which is a feeling I got from Groovy in some places.

Enough overview. Let's look at code.

Hello, Scala

OK, Scala really isn’t all that interesting as a Hello World program, but it does highlight one of the more interesting elements of Scala that I already like:

object Hello {
  def main(args: Array[String]): Unit = {
    Console.println(“Hello, Scala!”);
  }
}
First, we see the “object” keyword where “class” would be expected in Java; this means that this is a singleton object, and Scala will handle the construction of the singleton instance as well as the prevention of any further constructions. Singletons have become so prevalent in Java (and other OO languages) that it just makes a lot of sense to make it a first-class language entity. There’s some other interesting elements in that sample that differ from the traditional Hello Java program, but we’ll leave that alone for now. Put this code into App.scala (once again, another language has corrected Java’s requirement that filename-match-classname, which I’ve always found odious and annoying), compile it with scalac, and you get a slew of .class files out the other end. Run the program with the “scala launcher” (which is a simple batch file around the Java launcher, to ensure the Scala support libraries are on the classpath) with scala Hello, and you get the expected result.

Some of what's interesting to see here is that the Scala compiler actually produced two .class files--one entitled App.class, another called App$.class, the second App$ class apparently to provide "module" behavior (which I suspect is related to the singleton-ness of the object declaration in the code). As you might expect, Scala injects some additional support methods into both classes, including getScalaType, which is obviously intended to return the type of the object to Scala, just as the .class or getClass does for Java. Which brings up another interesting point.

Scala presents a unified type hierarchy, such that scala.Any is the root of the type system, and (like the CLR) is bifurcated into two basic elements, one being the object-family of types (java.lang.Object, known to Scala as scala.AnyRef) and the "primitive type" family of types, known to Scala as scala.AnyVal. Scala calls these reference classes and value classes, respectively--the same monikers the CLR uses. There's also reference to a type scala.All, which the introduction/tutorial page puts at the bottom of the type hierarchy, apparently inheriting from everything, but I'm can't find documentation on it or what purpose it serves. *shrug* More on that later, I guess.

Another interesting tidbit is that we can run Scala interpretively, the same way we can do to Groovy:

> scalaint -nologo HelloWorld.scala
> HelloWorld.main(null)
Hello, world!
(): scala.Unit
>:q
Which implies, then (though I haven't done it yet), that the Scala language could be used as a DSL to analysts and/or domain experts within an existing Java application.

Update: Forgot to mention, Scala has another interesting element to it that makes it very interesting to Ruby in much the same way:

object HelloWorld2 with Application { 
  Console.println("Hello, world!"); 
}
The with Application clause makes the entire content of the class basically a single script, as if the def main method has been declared to be the entire body of the class. This makes Scala very interesting as a potential scripting language, since now no explicit entry point need be defined; you can assume it's already present and accounted for, yet still relies on the underlying rules of the JVM (that the entry point must be defined as a static method, blah blah blah). Describing how with Application works is a bit difficult to describe without going into larger detail on other topics, so I'll leave that for a future discussion or (as book authors are so fond of writing) as an exercise to the reader to figure out. :-)

I consider myself a relative newbie to Scala, but as I progress through the language and see some useful applications of features, I will blog more. I'll also blog some of the features themselves, but you can find that for yourself by working through the Scala tutorial material on the site, if you're so inclined. In the meantime, catch the presentation I'm doing on Scala at the No Fluff Just Stuff symposiums, starting 2Q this year.

And, by the way, for those of you in the .NET space, Scala does, as I mentioned before, cross-compile to .NET assemblies, though I haven't spent much time exploring this. Frankly, I'd be more comfortable using Scala in the .NET world if there was a .NET-based compiler for it, rather than having to install a JRE just to run the compiler, but F# serves much the same space in the .NET world that Scala does here, and that's another language I'm pursuing with some vigor, as well. More on that later. :-)