The One Lab

Groovy, Scala, and Clojure, oh my!

Tue Nov 9, 2010 13:41:00 -0700

It's been a while since I've posted, but I just came across something rather interesting: a programming language called Groovy, which is supposed to make Java more palatable. So at work we had a quick presentation on the subject, and during said presentation I took some time to pull down Groovy and start hacking away while listening. In about fifteen minutes I had a fibonacci function running, and five minutes after that I had a simple mail delivery system setup. Here's the code:

class Letter {
    def from
    def to
    def subject
    def content

class LetterBomb extends Letter {
    def getContent() {
        println "It's a bomb! KABOOOOOM!"

class Mailbox {
    def owner
    def letters = []

    def shouldGetLetter(letter) {
        return == owner

    def addLetter(letter) {
        letters << letter

mailboxes = [
    new Mailbox(owner:"zooba"),
    new Mailbox(owner:"foo")

letters = [
    new Letter(to:"zooba", from:"foo", subject:"Test letter", content:"Wheeee!"),
    new Letter(to:"foo", from:"zooba", subject:"Go away!", content:"GO AWAY!"),
    new LetterBomb(to:"foo", from:"zooba", subject:"MUHAHAHA")

for (letter in letters) {
    for (mailbox in mailboxes) {
        if (mailbox.shouldGetLetter(letter)) {
            mailbox.addLetter letter
            println "Delivered letter from ${letter.from} to ${mailbox.owner}"

for (mailbox in mailboxes) {
    println ""
    println "Hey, I'm ${mailbox.owner}"

    for (letter in mailbox.letters) {
        println "I got a letter from ${letter.from} about ${letter.subject}"
        println "It says ${letter.content}"

The output is something like this:

Delivered letter from foo to zooba
Delivered letter from zooba to foo
Delivered letter from zooba to foo

Hey, I'm zooba
I got a letter from foo about Test letter
It says Wheeee!

Hey, I'm foo
I got a letter from zooba about Go away!
It says GO AWAY!
I got a letter from zooba about MUHAHAHA
It's a bomb! KABOOOOOM!
It says null

Wacky, no? The syntax is pretty much the same as Ruby -- if you've used it, then hacking in Groovy is pretty easy.

Post a comment

blog comments powered by Disqus