Implementing Your Own Control Structures in Scala

I just discovered that Scala has the necessary power to handle implemention of custom control structures without any ugliness. The secret ingredient is that Scala has call-by-name parameters. Here’s an example (note the =>):

def unless[A](condition: Boolean, ifFalse: => A, ifTrue: => A) =
  if (condition) ifTrue else ifFalse

Demonstration: Scala won’t evaluate ifFalse or ifTrue unless necessary, like here:

unless(true, throw new Error, "Hello!") 
=> "Hello!"