Download NetBeans!

20080725 Friday July 25, 2008

Idiomatic Groovy

The code shown in my screenshot yesterday was correct Groovy but not idiomatic Groovy. This was the method in question:

String setSearchString(searchString) {

    def xml = proxy.GetSpeech(searchString)
    def XmlParser parser = new XmlParser()
    def speech = parser.parseText (xml)
    "PLAY: " + speech.PLAY.text() +
      "\nSPEAKER:" + speech.SPEAKER.text() +
      "\nTEXT:" + speech.text()

}

In Java, new lines need to be closed with a quote and contain the "+" character. In Groovy, although the above is perfectly acceptable, one can use triple-quotes for multi-lines. Even nicer, in this case, is to use GStrings (expressions declared inside double-quotes), together with Expandos (dynamic collections), instead:

String setSearchString(searchString) {

    def xml = proxy.GetSpeech(searchString)
    def XmlParser parser = new XmlParser()
    def speech = parser.parseText (xml)

    Expando result = new Expando()
    result.play = "PLAY: ${speech.PLAY.text()}"
    result.speaker = "SPEAKER: ${speech.SPEAKER.text()}"
    result.text = "TEXT: ${speech.text()}"
    result.all = "$result.play\n$result.speaker\n$result.text"

}

Much neater, more readable, and the result is the same as before. Plus, it could probably be improved even further.

Jul 25 2008, 09:57:08 AM PDT Permalink

Trackback URL: http://blogs.sun.com/geertjan/entry/idiomatic_groovy
Comments:

How about this?

["PLAY: ${speech.PLAY.text()}\n",
"SPEAKER: ${speech.SPEAKER.text()}\n",
"TEXT: ${speech.text()}"].sum("")

or if you do this a lot try this:

class AddLines
{
def val
def plus(obj){new AddLines("val":(val ? "$val\n$obj" : obj))}
String toString(){ val }
}

["PLAY: ${speech.PLAY.text()}",
"SPEAKER: ${speech.SPEAKER.text()}",
"TEXT: ${speech.text()}"].sum(new AddLines())

Posted by Dale Frye on July 25, 2008 at 03:00 PM PDT #

Post a Comment:

Name:
E-Mail:
URL:

Your Comment:

HTML Syntax: NOT allowed