by Malcolm Rowe

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:

… you can do that in Scala with by-name parameters. This code here uses implicits to add a ?? operator to any type in a specific namespace and uses by-name parameters to not eval any arguments it doesn’t need. A parameter of type => A means by name.
Blair Zajac, by email

Here’s the code he provided:

class OrTest[A](o : => A) {
  def ??(other : => A) = {
    if (null != o) {
    else {

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 ?? 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:

Scala’s certainly something I’m adding to my (ever-growing) list of ‘must look into this sometime’!