Module 1
Module 1
Groovy Fundamentals
Module Overview
• Object Oriented
• Platform Independent
• Simple
• Secure
• Architecture-neutral
• Portable
• Robust
• Multithreaded
• Interpreted
• High Performance – JIT
• Distributed
• Dynamic
Intro. To Groovy
• OOP
• Through Apache Licence
• Optionally compiled
• Runs in JVM
• Compiles down to Java byte-code
• Simplified syntax
• Support both Static and dynamically typed
• Support for operator overloading.
• operator overloading
• Native syntax for lists and associative arrays
• Native support for regular expressions
• Native support for various markup languages
• You can use existing Java libraries
• Groovy extends the java.lang.Object
Differences between Groovy and Java
• Default imports
• Multi-methods
• Array initializers
• Package scope visibility
• ARM blocks - Automatic Resource Management
• Inner classes
• Static inner classes
• Anonymous Inner Classes
• Creating Instances of Non-Static Inner Classes
• Lambdas
• GStrings
• String and Character literals
• Primitives and wrappers
• Behaviour of ==
• Conversions
• Extra keywords
Default imports
• Following
• Can be written as
Inner classes
UnSupported Supported
Lambdas
Groovy Java
Java 8 supports lambdas Has Closures
Runnable run = () -> Runnable run = { println
System.out.println("Run 'run' } list.each { println
"); it } // or
list.forEach(System.out: list.each(this.&println)
:println);
Scripting Languages
The old new new thing…
16
Scripting Languages – Productivity
7
6
5
4
3
2
1
0
lk
va
l
++
C
n
an
r
si
Pe
ho
lta
Ja
C
Ba
r tr
al
t
Py
Fo
Sm
al
su
Vi
S
M
17
Scripting Languages – The Reputation
• Weakly Typed
• Procedural
• Scalability / Enterprise Ready
• Not Maintainable – (Perl)
• Lack of threading support
• Lack of IDE / Debugger support
• Cross Platform Support
• Performance
• Specialized / Not general purpose
18
Scripting Languages – The Reality
19
Groovy – In the Sweet Spot
20
Groovy - Overview
22
Direct or Precompiled Modes
23
Groovy – Current Situation
24
Hello World – Groovy Style
26
Types Example
a is java.lang.Integer
b is java.lang.String
c is java.lang.Integer
d is java.lang.Float
27
Operator Overloading
28
Strings
29
String Example
me = 'Tarzan'
you = 'Jane'
line = "me ${me} - you $you"
assert line == 'me Tarzan - you Jane'
// Note abbrev dollar syntax $you
// Note == is equality not identity
30
String Example Continued
// Multi line
sql = """
SELECT FROM MyTable
WHERE Year = $date.year
"""
31
Regular Expressions
• Find Operator: =~
Creates a matcher.
• Match Operator: ==~
Matches a regular expression.
• Pattern Operator: ~String
Creates a pattern from a string.
32
Regular Expression Example
// Find operator
assert "aaa1bbb2ccc3" =~ /bbb/
// Patterns
def p = ~/a*b/
assert p instanceof Pattern
def m = p.matcher("aaaaab");
assert m.matches()
33
Ranges
assert (0..10).contains(0)
assert (0..10).contains(5)
assert (0..10).contains(10)
assert (0..10).contains(-1) == false
assert (0..10).contains(11) == false
assert (0..<10).contains(9)
assert (0..<10).contains(10) == false
assert ('a'..'c').contains('b')
log = ''
35
Lists and Maps
36
Lists - Specifying
myList = [1,2,3]
assert myList.size() == 3
assert myList[0] == 1
assert myList instanceof ArrayList
emptyList = []
assert emptyList.size() == 0
longList = (0..1000).toList()
assert longList[555] == 555
37
Lists – Overloaded Subscript Operator
myList = ['a','b','c','d','e','f']
// putAt(Range)
myList[0..2] = ['x','y','z']
assert myList == ['x','y','z','d','e','f']
myList[3..5] = []
assert myList == ['x','y','z']
myList[1..1] = ['y','1','2']
assert myList == ['x','y','1','2','z']
38
Lists – Negative Indexes
• Count from the back of the list. The last index is -1.
• Can be used with ranges.
• list[-3..-1] gives you the last three entries.
• list[1..-2] to cut away the first and the last entry.
39
Lists – Adding and Removing
myList = []
myList = []
myList << 'a' << 'b' // leftShift is like 'append'
assert myList == ['a','b']
40
Lists – GDK Methods
41
Lists Iteration with Closures
42
Maps - Specifying
43
Maps - Access
// retrieve
assert myMap['a'] == 1
assert myMap.a == 1
assert myMap.get('a') == 1
// assign
myMap['d'] = 1
assert myMap.d == 1
myMap.d = 2
assert myMap.d == 2
44
Maps - Iteration
45
Closures
47
Closures - Calling
// Create a closure
def adder = { x, y -> return x + y }
// Abbreviated call
assert adder(4, 3) == 7
// In a method
void adjustSalary(Closure adjustment) {
for(e in employees) {
adjustment(e)
}
}
48
Groovy Truth
Broader than Java which just uses Boolean tests to determine truth.
49
Switch Statement
Object a.equals(b)
Class a.isInstance(b)
Collection a.contains(b)
Range a.contains(b)
Pattern a.matcher(b.toString()).matches()
Closure a.call(b)
50
Switch Statement Example
switch (10)
{
case 0 : assert false ; break
case 0..9 : assert false ; break
case [8,9,11] : assert false ; break
case Float : assert false ; break
case {it%3 == 0}: assert false ; break
case ~/../ : assert true ; break
default : assert false ; break
}
51
Looping
52
Exceptions
53
Classes
54
Class – Field Access
class Counter {
public count = 0
}
def counter = new Counter()
55
Class – Overriding Field Access
class PretendFieldCounter {
public count = 0
Object get (String name) { return 'pretend value' }
void set (String name, Object value) { count++ }
}
def pretender = new PretendFieldCounter()
56
Method Declaration
• Public by default
• void returns can be omitted
• Types in argument list can be omitted, Object
assumed.
• Dynamic dispatch used to resolve methods.
• Defaults allowed in argument list.
• Optionals parameters if last argument is Object[]
• Common practice to use Maps for 'named'
arguments.
57
Method Example
class Summer {
def sumWithDefaults(a, b, c=0) { return a + b + c }
// Normal . operator
assert map.a.b.c == 1
// Safe dereferencing
assert map?.a?.x?.c == null
59
Constructors
• If explicit can
Employee emp3 = ['Tom', 50]
• By default groovy
imports the following
packages into all .groovy
files
• import java.lang.*
• import java.util.*
• import java.io.*
• import java.net.*
• import groovy.lang.*
• import groovy.util.*
• import java.math.BigInteger
• import java.math.BigDecimal
Object x = 1
Object y = 'foo'
63
GroovyBeans
64
GroovyBeans Example
d = new Date()
println d.time // can access this as a property
65
GroovyBean Properties
66
Spread Dot Operator
// Java approach
for(Iterator i = list.iterator(); i.hasNext();)
System.out.println(((Person) i).getName());
// Closure
println list.collect{ p -> p?.name }
// Output
[getBinding, getClass, getMetaClass, getProperty]
68
GPath Example2
class LineItem {
Product product; int count;
int total() {
return product.dollar * count
}
}
// find all product names with a line item totals > 7000
invoices.items.grep{it.total() > 7000}.product.name
70
Other Topics
71
Question