13Apr/090
Scala and DSLs
Tonight I wrote something quick in Scala to make a small DSL (just for fun).
I started with a small Email class:
class Email(name:String, address:String) { def standardForm = name + " <" + address + ">" override def toString = this.standardForm }
which is really stupid: it wraps a name along with an email address, and it adds a convenient textual output form.
Now I would like to be able to write something like:
val me = "Julien Ponge" is "julien" at "gmail.com" println(me)
To do that I wrote a simple builder:
class EmailBuilder(name:String) { var id:String = "" def is(str:String):EmailBuilder = { id = str this } def at(str:String):Email = { new Email(name, id + "@" + str) } }
then an implicit conversion function:
implicit def emailBuilder(name:String):EmailBuilder = new EmailBuilder(name)
And that's it.
You should always learn new languages: they are all worth something great! Be polyglot, seriously.
By the way I heard that some of the Scala features are coming to the next major version of Groovy, which is going to be exciting!
Related posts:
- If you have sent me an email about IzPack…
- Groovy and EJBs
- Guice it up (or AOP can be made simple sometimes)
- Creating namespaces with functions in JavaScript
- Playing with Berkeley DB Java Edition and Guice

