10. Groovy is like a super version of Java. It can
leverage Java's enterprise capabilities but also has
cool productivity features like closures, DSL support,
builders and dynamic typing.
Groovy = Java – boiler plate code
+ optional dynamic typing
+ closures
+ domain specific languages
+ builders
+ meta programming
2010-10-9 10
24. Operator Method
a + b a.plus(b)
Operator Overloading a - b a.minus(b)
a * b a.multiply(b)
◦ Groovy支持的运算符 a ** b a.power(b)
◦ http://groovy.codehaus.org/Operators a / b a.div(b)
◦ http://groovy.codehaus.org/Operator+Overloading a % b a.mod(b)
a | b a.or(b)
◦ 例子: a & b a.and(b)
◦ 10 ** 3 = 1000 a ^ b a.xor(b)
◦ ~”.*http.*” (把一个String换成一个Pattern) 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.leftShift(b)
a >> b a.rightShift(b)
switch(a){ case(b): } b.isCase(a)
~a a.bitwiseNegate()
-a a.negative()
Safe Dereferencing +a a.positive()
◦ s?.size() a == b a.equals(b) or
◦ ===> null a.compareTo(b) == 0 **
a != b ! a.equals(b)
Autoboxing 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
2010-10-9 24
25. 5/3 = 1.66666667
5.intdiv(3) = 1
类型后缀
G java.math.BigInteger 55G
L java.lang.Long 55L
I java.lang.Integer 55I
G java.math.BigDecimal 3.14G
D java.lang.Double 3.14D
F java.lang.Float 3.14F
2010-10-9 25
26. class X
{
def field
def getField()
{
field += 1
}
}
x = new X()
x.field = 1
println x.@field // 1
println x.field // 2
2010-10-9 26
34. def r = 1..3
println r.class
===> groovy.lang.IntRange
r.each{println it}
===>
1
2
3
def r = 1 ..< 4
===> 1, 2, 3
def today = new Date()
===> Sat Dec 29 23:59:28 MST 2007
def nextWeek = today + 2
===> Sat Jan 05 23:59:28 MST 2008
(today..nextWeek).each{println it}
===>
Sat Dec 29 23:59:28 MST 2007
Sun Dec 30 23:59:28 MST 2007
Mon Dec 31 23:59:28 MST 2007
2010-10-9 34
35. def x = 1.23
switch ( x ) {
case "foo“:
println “String foo”
case ~/d+/:
println “String numbers”
case [4, 5, 6, 'inList']:
println “In List”
case 12..30:
println “In Range”
case Integer: 在Groovy中,类名表示class对象,即
println “A Integer” Integer == Integer.class
default:
println “Oops!”
}
2010-10-9 35
36. def hi = { println "Hi"}
hi()
===> Hi
def calculateTax = { taxRate, amount ->
return amount + (taxRate * amount)
}
println "Total cost: ${calculateTax(0.055, 100)}"
===> Total cost: 105.500
def tax = calculateTax.curry(0.1)
[10,20,30].each{
println "Total cost: ${tax(it)}"
}
===>
Total cost: 11.0
Total cost: 22.0
Total cost: 33.0
2010-10-9 36
37. how simple, elegant, and flexible your code is when you take advantage of
dynamic typing? But, is this risky business?
• You might mistype the method name when creating one of the helpers.
• Without the type information, how do you know what to send to your
method?
• What if you send a object(which haven’t the methods) to the method?
Programming with dynamic typing without having the discipline of unit
testing is playing with wildfire.
2010-10-9 37