X

Geertjan's Blog

  • July 25, 2008

Idiomatic Groovy

Geertjan Wielenga
Product Manager
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.

Join the discussion

Comments ( 1 )
  • Dale Frye Friday, July 25, 2008

    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())


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.