On Scala
Shortly after I posted my previous entry about providing a language feature to declare deferred evaluation semantics for function arguments (which I termed, loosely, ‘auto-lambda-isation’), Blair Zajac wrote to let me know that Scala (about which I knew almost nothing) supports exactly this feature:
Here’s the code he provided:
class OrTest[A](o : => A) {
def ??(other : => A) = {
if (null != o) {
o
}
else {
other
}
}
}
object Test extends Application {
implicit def anyToOrTest[A](o : A) : OrTest[A] = { new OrTest(o) }
val s1 = "string1"
val s2 : String = null
val s3 = "string3"
println(s1)
println(s1 ?? s2)
println(s2 ?? s3)
}
(The example above is evaluating simple strings, but Blair’s original example included methods as well, but since they look exactly the same as the usages above, I’ve skipped them here.)
Incidentally, Scala looks really quite interesting: skimming through the Scala tutorial, I see some notable things:
- the compiler produces normal Java bytecode (and there also appears to be another compiler for CLR)…
- … and so interoperability with existing Java code is trivial: you can use
Scala from Java, and you can import any existing Java class straight into
your Scala program without having to worry about marshaling or odd call
syntaxes (
java.lang
is imported by default, for example). - it seems to support most of what you’d expected from a modern OO language,
including support for generics and treating functions as first-class objects
(the example above demonstrates both;
[A]
is the Scala equivalent of Java or C++’s<T>
syntax for declaring generic placeholders). It also appears to support a limited form of multiple inheritance, which is interesting particularly, as Java — and therefore the bytecode output from the Scala compiler — doesn’t. - everything’s an object, including literals:
1 + 2 * 3
is equivalent to the method calls1.+(2.*(3))
. - there’s a rather intriguing use of pattern matching to define functions that looks distinctly… functional. I haven’t quite grokked it yet.
Scala’s certainly something I’m adding to my (ever-growing) list of ‘must look into this sometime’!