Partly hands-on
Getting Groovy links:
Groovy is Java on steroids
Add the [GROOVY_HOME]\bin directory to your system path.
Linux/Mac OS X: open your shell and set the PATH variable
> export PATH=$PATH:$GROOVY_HOME/bin
To validate the installation we open a command prompt or console and type:
> groovy -version
Locally with Groovy Console
> groovyConsole
Or use Groovy web console
public class UsingJava {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public String toString() {
return "Using Java " + getName();
}
public static void main(String[] args) {
UsingJava usingJava = new UsingJava();
usingJava.setName("Geeks");
System.out.println(usingJava);
}
}
class UsingJava {
String name
String toString() {
"Using Java $name"
}
static void main(String[] args) {
UsingJava usingJava = new UsingJava(name: ‘Geeks’)
println usingJava
}
}
Basic types
// dynamic type
def s = 'Hello'
assert s instanceof String
s = 42
assert s instanceof Integer
// GString
def user = 'mrhaki'
def greeting = "Hi, ${user}. Your name has ${user.size()} characters"
assert greeting == 'Hi, mrhaki. Your name has 6 characters'
Methods
class User {
String username
String greeting(salutation = 'Hello') {
"${salutation}, ${username}."
}
}
User user = new User(username: 'mrhaki')
assert user.username == 'mrhaki'
user.setUsername('Hubert')
user.username = 'Hubert'
assert user.greeting() == 'Hello, Hubert.'
assert user.greeting('Hi') == 'Hi, Hubert.'
Basic
Closures as method arguments
def gr8 = { arg1, arg2, arg3 = 'gr8conf' ->
"$arg1 $arg2 $arg3"
}
println gr8("I'm","going to")
def cl = gr8.ncurry(1,'love')
def m(arg, closure) {
println closure(arg)
}
m('I',cl)
Looping
Finding data
Transforming data
def list = ['abc', 100, 'defg', false]
assert list.findAll { it instanceof String } == ['abc', 'defg']
assert list.any { it instanceof String && it.size() >= 4 }
def map = [key: 'value', otherKey: 42, name: 'mrhaki']
assert map.collect { key, value ->
"${key} = ${value}" } == ['key = value', 'otherKey = 42', 'name = mrhaki']
No boilerplate
Create XML
Read XML
import groovy.xml.*
def url = "http://mrhaki.com/books.xml".toURL()
def slurper = new XmlSlurper()
def xml = slurper.parseText(url.text)
println xml.book.collect { it.title }
println xml.book.find { it.@id == '2' }.title
Examples of AST transformations
Non-existing methods/properties
Embedded into