Search code examples
scalaif-statementkeywordcontrol-flow

Could Scala's “if … else” have been implemented as a library function?


I'm wondering if if … else could have been implemented in Predef with special compiler treatment, in a similar way to what's being done with classOf[A]: the definition is in Predef, the implementation is filled in by the compiler.

Granted, many people would find reassuring to know that an if is always an if, and an else is always an else, no matter the context. However, defining else as a method on the result type of if would remove it from the list of keywords, and allow library designers to define their own else methods. (I know I can use any keyword as an identifier with backticks, but something like `else` just looks awful in code.) Such methods could be useful in cases discusses in situations such as this one, discussed on the mailing list, where people are forced to use otherwise when defining methods that actually should be named else. (Also discussed on SO here and here.)

So:

  • Would such an approach be possible, even in theory, or does it break some fundamental principle in Scala?
  • What would the downsides be?

Solution

  • Maybe I don't understand your question, but you can already implement if ... else ... as a library function. Consider this:

    class If[A](condition: =>Boolean)(ifBlock: =>A) {
      def els(elseBlock: =>A):A = condition match {
        case true => ifBlock
        case false => elseBlock
      }
    }
    
    new If(2==3)(
      println("equal")
    ) els (
      println("not equal")
    )
    

    Of course this doesn't do exactly what if ... else ... does, but with some polishing I think it would. I once implemented a very simple interpreter for a language that had pattern matching built in with if ... else ... being implemented in much the same way I did here.