JPz'log Coin Coin and Plop da Plop

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!

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Live
  • Netvibes
  • StumbleUpon
  • Technorati
  • FriendFeed
  • Wikio
  • Twitter
  • Identi.ca
  • Reddit
  • RSS
  • Slashdot

Related posts:

  1. If you have sent me an email about IzPack…
  2. Groovy and EJBs
  3. Guice it up (or AOP can be made simple sometimes)
  4. Creating namespaces with functions in JavaScript
  5. Playing with Berkeley DB Java Edition and Guice

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

JPz'log is Digg proof thanks to caching by WP Super Cache