Groovy classes compile down to Java bytecode and so there's a 1-1 mapping between a Groovy class and a Java class. Indeed each Groovy class can be used inside normal Java code - since it is a Java class too. Probably the easiest way to get groovy is to try working with collections. In Groovy List (java.util.List) and Map (java.util.Map) are both first class objects in the syntax. So to create a List of objects you can do the following... Note that in the following snippets of Groovy code, the groovy> means a command line prompt - you don't need to type this. groovy> list = [1, 2, 'hello', new java.util.Date()] groovy> list.size() 4 groovy> list.get(2) 'hello' Notice that everything is an object (or that auto-boxing takes place when working with numbers). To create maps... groovy> map = ['name':'James', 'location':'London'] groovy> map.size() 2 groovy> map.get('name') 'James' groovy> list = [1, 2, 3] groovy> for (i in list) { println(i) } 1 2 3 Closures are similar to Java's inner classes, except they are a single method which is invokable, with arbitrary parameters. A closure can have as many parameters as you wish... groovy> closure = { param | println("hello ${param}") } groovy> closure.call("world!") hello world! groovy> closure = { greeting, name | println(greeting + name) } groovy> closure.call("hello ", "world!") hello world! groovy> closure = { println("hello " + it) } groovy> closure.call("world!") hello world! allows you to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing groovy> [1, 2, 3].inject('counting: ') { str, item | str + item } "counting: 123" groovy> [1, 2, 3].inject(0) { count, item | count + item } 6 In addition there's 2 new methods for doing boolean logic on some collection... returns true if all items match the closure predicate groovy> [1, 2, 3].every { it < 5 } true groovy> [1, 2, 3].every { item | item < 3 } false returns true if any item match the closure predicate groovy> [1, 2, 3].any { it > 2 } true groovy> [1, 2, 3].any { item | item > 3 } false returns the max/min values of the collection - for Comparable objects groovy> [9, 4, 2, 10, 5].max() 10 groovy> [9, 4, 2, 10, 5].min() 2 groovy> ['x', 'y', 'a', 'z'].min() 'a' concatenates the values of the collection together with a string value groovy> [1, 2, 3].join('-') '1-2-3' class Foo { myGenerator(Closure yield) { yield.call("A") yield.call("B") yield.call("C") } } foo = new Foo() for (x in foo.myGenerator) { print("${x}-") } class Foo { myGenerator(yield) { yield "A" yield "B" yield("C") } } |