Friday, January 21, 2011

Scala DSL - realistic looking options

Trying to simulate the way options are passed to unix commands via '-'.

The idea is to define a set of applicable flags and an - operator. The end result is being able to write this beauty:

rm -r -f apply "gigi.file"
Without further ado, here's the sample code:



We're limiting the flags and making this type-safe with the Flag case class. If you had more types of commands, you could limit the actual flags for each of them with custom Flag classes.

The main idea is counting on scala's infix notation. The different flags accumulate in sequence and in the end, the resulting command (now with flags) is applied.

The magic of the infix notation is revealed by this equivalent form:


rm.-(r).-(f).apply("gigi.file")
Further things to consider:

  • combining options
  • simplifying away the "apply" from the syntax

This sample is available here and I wrote it while playing with a unix-looking scala shell for file management: https://github.com/razie/scalafs.

Have fun!