MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

Groovy

Mike Calvo

mike@citronellasoftware.com


What Is Groovy?


Similarities with Java


Example Syntax Differences


More Syntax Differences


Groovy and Properties


A Simple Example

class Person {
  String firstName
  String lastName
  Date dateOfBirth
}

Groovy Strings

  "${firstName} ${lastName}"
"""Name: ${firstName} ${lastName}
          Date of Birth: ${dateOfBirth}"""

Dynamically Typed

def s = a string value // s is a string
def foo() { return 0 } // foo defined to return an int

Collections

def list = ['a', 'b', 'c']
def map = [firstName: 'Mike', lastName: 'Calvo']

Closures


Closure Arguments


Closure Examples

def log = { String message -> println message }
log('hi')

log = { println it }
log('bye')

def adder = { a, b -> a + b }
println adder(1,2)


Groovy Style

When defined inline closures are usually passed as arguments outside the parenthesis

// Closure is argument to eachLine
new File('foo.txt').eachLine { println it }

// Closure is argument to constructor
new Thread { while(true) { sleep(500); check() } }

Truth and Falsehood


Duck Typing

“If something walks like a duck and quacks like a duck then I can refer to that thing as a duck”


Maps as Duck Types


Parsing Structured Data


Example Slurping/Building

def response = JsonSlurper.parse('{"name": "Mike", "dob": {"month": 7 }}')
assert response.name == 'Mike'
assert response.dob.month == 7

def builder = new JsonBuilder()
def root = builder.people {
  person {
    name 'Mike'
    dob(month: 7)
  }
}
assert builder.toString() == '{"people":{"name":"mike", "dob":{"month": 7}}}'

Difference from Java: Imports

import java.io
import java.lang
import java.net
import java.util
import groovy.lang
import groovy.util

Difference from Java: in Keyword

in is a keyword used to define ranges

  for (x in 0..5)

Difference from Java: Array Declaration


Complete List of Groovy/Java Differences


Groovy Style


Example Operator Overloads

def list = ['a', 'b']
list += 'c'
list << 'd'

list = [new Person(name: 'mike'), new Person(name: 'matt')]
assert list*.name == ['mike', 'matt']

def map = [name: 'Mike'] + [dob: new Date()]
assert map.dob
assert map.name == 'Mike'

Groovy Meta Programming


Meta Programming Tools


Groovy Console