Wednesday, April 23, 2008

Java Programmer looking at Groovy

Some things that might help you when looking over Groovy code with "Java" eyes:

  • everything is an object!
  • method parenthesis are optional
  • semicolons at the end of the line are optional
  • elements in brackets are either a List() or a Map()
    • Lists are comma separated elements
      • def myList = ["one", "two", "three"]
    • Maps are name value : pairs separated by commas
      • def myMap = [dairy:"cheese", meat:"chicken", shopper:"Mario"]
  • the return keyword is optional
    • by default the result of the last statement in a code block is returned
  • The questionmark protects you from null pointer exceptions
    • println myObj?.myAttribute will print myAttribute if myObj is not null, no error thrown
  • Strings can be single or double quoted
  • Double quoted strings can have variables nested with using the ${ var } syntax or simply $var
    • def var = "Crusty"
    • println "The clown $var unnerves me"
  • The ampersand allows you to call a method from an object
    • println myObj.&someMethod
  • The at symbol allows you to directly address a classes attribute
    • myObj.@fieldName = "somevalue"
  • A range of elements can be defined using an elipsis
    • (1..10).each {println "toe number $it"}
  • Now that opened up a couple of other items....
  • Code in braces is called a closure (see other blog "What are Groovy Closures?")
  • the keyword "it" is the default iterator for a closure
  • The double less than symbol is used for appending with StringBuffer, Lists, Sockets, Files & Writers
  • Named Parameters
    • For example, create a new user with a name and ssn provided
    • new User (name:"Gorge", ssn: "123-45-9999")
  • Parameter Defaults
    • def myMethod (String name, String type="chef") { //somecodehere }

No comments: