4. Agenda
• What is Groovy ?
• Candies
• Closures
• Dynamic Groovy
• Groovy builders
• Integrating java and groovy
• More Groovy Cool Stuff
5. #!/usr/bin/ruby
class Person
def initialize(lname, fname)
@lname = lname
@fname = fname
end
attr_reader :lname, :fname
attr_writer :lname, :fname
end
steve = Person.new("Litt", "Stove")
print "My name is ", steve.fname, " ", steve.lname,
".n"
steve.fname = "Steve"
print "My name is ", steve.fname, " ", steve.lname,
".n"
7. What is Groovy ?
• “Groovy is what Java would look like had it been written
in the 21st century.”
• an agile and dynamic language for the JVM
• inspired by languages like Python, Ruby and Smalltalk
• compiles straight to Java bytecode, integrates natively
with java
• compiled or interpreted
• supports Domain-Specific Languages and other compact
syntax
8. Other Cool Features
●
expressive java-like syntax
●
same oo and libs and java properties
●
suports strong/weak typing
●
operator overloading
●
Gstrings
●
Closures
●
Almost 0 learning curve for java developers
9. J ava G roovy G roovy
import java.util.List; import java.util.List; class Speaker {
import java.util.ArrayList; import java.util.ArrayList; def age
String name
public class Speaker { public class Speaker {
private Integer age; String toString() {
private Integer age;
private String name; private String name; return "${name} - $age"
}
public String toString() { public String toString() { }
return name + " - " + age; return name + " - " + age;
} }
def speakers = [
public Integer getAge() { public Integer getAge() { new Speaker(name: "john", age: 15) ,
return age; return age; new Speaker (name: "ionel", age: 29)
} } ]
public void setAge(Integer age) { public void setAge(Integer age) {
this.age = age; def upper = {it.toString().toUpperCase()}
this.age = age;
} }
speakers.findAll{s -> s.age >20}
public String getName() { public String getName() { .collect(upper).each{println it}
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public static void main(String[] args) { public static void main(String[] args) {
List<Speaker> speakers = new List<Speaker> speakers = new ArrayList<Speaker>();
ArrayList<Speaker>(); Speaker ion = new Speaker();
Speaker ion = new Speaker(); ion.setName("Ion");
ion.setName("Ion"); ion.setAge(15);
ion.setAge(15); Speaker john = new Speaker();
Speaker john = new Speaker(); john.setName("John");
john.setName("John"); john.setAge(25);
john.setAge(25);
speakers.add(ion);
speakers.add(ion); speakers.add(john);
speakers.add(john);
for(Speaker s: speakers){
for(Speaker s: speakers){ if (s.getAge()>20)
if (s.getAge()>20) System.out.println(s.toString().toUpperCase());
}
System.out.println(s.toString().toUpperCase()); }
} }
}
}
16. Operator Overloading
a+b a.plus(b)
a-b a.minus(b)
a*b a.multiply(b)
a ** b a.power(b)
a/b a.div(b)
a %b a.mod(b)
a|b a.or(b)
a&b a.and(b)
a^b a.xor(b)
a++ or ++a a.next()
a-- or --a a.previous()
a[b] a.getAt(b)
a[b] = c a.putAt(b, c)
a << b a.leftS hift(b)
a >> b a.rightS hift(b)
switch(a) { case(b) : } b.isCase(a)
~a a.bitwiseNegate()
-a a.negative()
+a a.positive()
a == b a.equals(b) or a.compareTo(b) == 0 **
a != b ! a.equals(b)
a <=> b a.compareTo(b)
a>b a.compareTo(b) > 0
a >= b a.compareTo(b) >= 0
a<b a.compareTo(b) < 0
a <= b a.compareTo(b) <= 0
17. GStrings
'Hello World'
“Hello $world”
/Hello $world/
if (text =~ pattern)println "match"
if (text ==~ pattern) println "match"
matcher ='Groovy is groovy'=~ /(G|g)roovy/
print "Size of matcher is ${matcher.size()} "
println "with elements ${matcher[0]} and ${matcher[1]}."
18. Closures
• A Groovy closure is like a "code block" or a method pointer. It is a
piece of code that is defined and then executed at a later point.
def clos={param -> println "Hello ${param}"}
clos.call(1)
clos('1')
1.upto(10) {p -> println p}
1.upto 10,clos
[1, 2, 3, 4].each {println it}
def isEven={x -> return (x % 2==0)}
def isOdd={x -> return ! isEven(x)}
def filter(list, predicate) {
return list.findAll(predicate)
}
def odds=filter(table, isOdd)
println “odds: ${odds}”
22. Files
new File(".").eachFile{file ->println file}
new File(".").eachFileMatch(~/.*.jsp/){file ->println file}
new File("x.txt").eachLine{line->println line}
file.splitEachLine(" "){words ->println words.size() ; wordCount += words.size() }
File file = new File("hello.txt")
file.write("Hello Worldn")
File src = new File("src.jpg")
new File("dest.jpg").withOutputStream{ out ->
out.write src.readBytes()
}
"cp ${src.name}${dest.name}".execute()
new File("src.txt").delete()
23. Dynamic Groovy
• “A domain-specific language, unlike a general-purpose
language, is designed to be useful for a specific task in a
fixed problem domain .”(MSDN)
24. Why Groovy
• The compiler doesn’t know much about behavior
• Behaviour completely dynamic at runtime
• Everything’s routed through the Meta Object
Protocol
– Method calls, property access, operators…
– That’s why Groovy is a “dynamic language”
26. What Groovy offers 2
class Pouncer {
static pounces(Integer self) {
(0..<self).inject("") {s, n ->
s += "boing! "
}
}
}
use(Pouncer) {
assert 3.pounces() == "boing! boing! boing! "
}
27. 1+1= 2!!!! Really ???
String.metaClass.plus={d->
if (delegate=="maria" && d == "ion") return "ghita"
delegate.concat d
}
println "maria"+"ion"
println "Tom"+"&"+"Jerry"
28. 1+1= ?
4.meters + 4.kilo.meters
class Distance {
static METER = 'meter'
def dist, type
Distance(a, b) {dist = a; type = b}
String toString() {"$dist $type"}
def plus(b) {
if (b.type == type) {
return new Distance(dist + b.dist, type)
}}}
Integer.metaClass.getMeters = {->
new Distance(delegate, Distance.METER)
}
Integer.metaClass.getKilo = {->
delegate * 1000
}
println 4.kilo
println 4.meters
println 4.meters + 4.kilo.meters
29. Testing and Mocks
def service = [retrieveRate:{ new ExchangeRate(1.45, 0.57) }] as
ExchangeRateService
def sterlingConverter = new SterlingCurrencyConverter(service)
service = { new ExchangeRate(1.55, 0.56) } as ExchangeRateService
sterlingConverter = new SterlingCurrencyConverter(service)
mockContext1 = new MockFor(ExchangeRateService)
mockContext1.demand.retrieveRate { new ExchangeRate(1.75, 0.54) }
def dummyService1 = mockContext1.proxyInstance()
30. Reading XML
• XmlParser/ XmlSlurper
import groovy.util.*
def parser = new XmlParser()
def doc = parser.parse(‘library.xml’)
println “${doc.book[0].title[0].text()}”
doc.book.title.each { title ->
println “${title.text()}”
}
31. Reading XML 2
person = new person = new XmlSlurper()
XmlParser().parse(file) .parse(file)
println person.attribute("id") println person.@id
println person["@id"]
println person["@id"]
println person
println person.text()