Upload
paul-woods
View
3.430
Download
1
Tags:
Embed Size (px)
DESCRIPTION
My slides for a talk given to the Dallas FortWorth groovy and grails user group.
Citation preview
Resources
http://groovy-almanac.org/http://mrhaki.blogspot.com/http://gr8forums.org/index.phphttp://groovyconsole.appspot.com/
Manning Groovy In Action ISBN 1-932394-84-2
Programming Groovy ISBN-10: 1-934356-09-3
List - create
create a list def list = [ 'q', 'w', 'e' ] println list
List – non typed elements
the items in a list are non-typed def a = [ 1, 1.1, 'a', new Date() ]
List – adding elements
add elements to a list – use left shift def list = ['q', 'w', 'e'] list << 'r' list << 't' list << 'y' println list
add a list to a list – use the plus list += [1,2,3] println list
List - iterating
loop though the elements in a list def list = ['q', 'w', 'e', 'r', 't', 'y']
for(def item : list) { println "by item : $item" }
for(def item in list) { println "by item in : $item" }
list.each { item -> println "by each : $item" }
List - transform
Transform a list def list = [1,2,3,4,5] def list2 = list.collect { it * 10 } println "list=$list" println "list2=$list2"
List – retrieving elements
Retrieving Elements def list = ['q', 'w', 'e', 'r', 't', 'y']
println "element 0 : ${list.get(0)}" println "element 1 : ${list[1]}" println "elements 1,3,5 : ${list[1,3,5]}" println "elements 0..3 : ${list[0..3]}" println "last 3 elements : ${list[-3..-1]} "
println "element last 3 : ${list[-3..-1]} "
List – removing elements
Removing Elements def list = ["q", "w", "e", "r", "t", "y"] println list list -= "q" println list list -= ["w", "e"] println list
List - sorting
Sorting Lists // note – original list is not changed
def list = ['q', 'w', 'e', 'r', 't', 'y'] def sorted = list.sort() println "list=$list" println "sorted=$sorted"
List – unique elements
Retrieving the unique elements // note – list is modified // note – list does not need to be sorted.
def list = ['a', 'b', 'c', 'a', 'b', 'c' ] println "list = $list" list.unique() println "list = $list"
List - find
Finding elements in Lists
def list = ['q', 'w', 'e', 'r', 't', 'y'] def letter = list.find { 'q' } println "find : $letter"
def letters = list.findAll { it < 't' } println "findAll : $letters"
println "all items below f : ${list.every { item -> item < 'f'} }"
println "any item below f : ${list.any { item -> item < 'f'} }"
List - join
convert list into a string def list = [ 'q','w','e','r','t','y'] println list.join("-")
List – advanced 1
sort a list of maps by first or last or last,first list = [ [first:"paul", last:"woods"], [first:"linda", last:"zinde"], [first:"alex", last:"zinde"], [first:"paul", last:"allen"] ]
// sorting by a value in a map println "sorted by first : ${list.sort { it.first } }" println "sorted by last : ${list.sort { it.last } }"
// sorting by 2 values
def sorted = list.sort { x, y -> (x.last <=> y.last) ?: (x.first <=> y.first)
} println "sort by last and first : ${sorted}"
List – advanced 2
transform a list of lists to a csv string
def list = [ [ "first", "last" ], [ "paul", "woods"], [ "linda", "zinde"], [ "alex", "zinde"], [ "paul", "allen"] ]
def csv = list.collect { row -> row.collect { item -> "\"$item\"" }.join(',') }.join('\n')
println csv
List - mystery
Why does this work? List<String> z = new ArrayList<String>() z << "A" z << 1 z << new Date() println z
? because generics in java are checked at compile time, and groovy doesn't check
Map - create
Create map def map = [ first : "Paul", last : "Woods" ]
println map
Tip – if you need iterate through your keys in order... def map = new TreeMap<String,String>()
Map – adding elements
Map - iterating
looping through maps def map = [ first : "Paul", last : "Woods" ]
for(keyValue in map) { println "keyValue=$keyValue" }
for(keyValue in map) { println "key=$keyValue.key, value=$keyValue.value" }
map.each { kv -> println "kv=$kv" } map.each { k, v -> println "k=$k, v=$v" }
Map – retrieving elements
retrieving elements def map = [ first : "Paul", last : "Woods" ]
println "map.first = $map.first" println "map['first'] = ${map['first']}"
def key = "first" def value = map."$key"
println "def key=\"$key\"; map.\"\$key\" = ${value}"
Map – removing elements
removing elements from a map def map = [ first : "Paul", last : "Woods" ] map.remove('first') println map
Map – find
finding elements def map = [ first : "Paul", last : "Woods"]
def result1 = map.find { kv -> kv.value == "Woods" } println result1.getClass() println result1
def result2 = map.findAll { kv -> kv.key != "last" } println result2.getClass() println result2
Range – the basics
Basic range operations def range = (1..5) println range println range.class range.each { n -> println n } println "contains 5 : " + range.contains(5) println "contains 7 : " + range.contains(7)
range.step(2) { println it }
def range2 = (new Date()-7 .. new Date()) range2.each { date -> println date }
Operation – ?. subscript
The method will not be called if the object is null.
def list = [ 'a', 'b', null, 'c', 'd' ]
// list.each { item -> println item.toUpperCase() }
list.each { item -> println item?.toUpperCase() }
Operation – ?: conditional
if object is false, return another object. else return the object
def q = null println "null : " + (q ?: "it is false")
q = "" println "empty : " + (q ?: "it is false")
q = "abc" println "value : " + (q ?: "it is false")
Operation - <=> - spaceship
calls the .compareTo method returns -1 if a < b returns +1 if a > b returns 0 if a == b
println "1 <=> 2 : " + (1 <=> 2) println "2 <=> 1 : " + (2 <=> 1) println "1 <=> 1 : " + (1 <=> 1)
Closures - introduction
A block of executable code, similar to a method, but it can be easily assigned to a variable, and passed to other methods.
def add = { a, b ->
a+b
}
println add(1,2)
Closure - example
A method that takes a closure
class Names {
def name1 def name2 def name3
def capitalize(Closure c) { c.call name1.capitalize() c.call name2.capitalize() c.call name3.capitalize() } }
def names = new Names(name1:'paul', name2:'mike', name3:'eric')
def greeting = { name -> println "Hello, " + name }
names.capitalize greeting
Closure - syntax
Syntax for zero, 1 and 2+ parameter closures
def zero = { -> println "zero parameters" }
def one_a = { println "one parameter : $it" }
def one_b = { a-> println "one parameter : $a" }
def two = { a, b -> println "two parameters : $a $b" }
zero.call() one_a.call('1a') one_b.call('1b') two.call('22', '2222')
MultiAssign
initialize or assign multiple variables with values from a list.
def a def b (a, b) = [ 1, 2] println "a=$a" println "b=$b"
def (c, d) = [ 3 , 4 ] println "c=$c" println "d=$d"
Optional parenthesis, semicolons, and returns
In some situations, groovy allows you to remove parenthesis, semicolons and return statements.
Optional – Parenthesis 1
No Arguments and no ‘get’ prefix – () mandatory class Name { def first, last def print() { println first + " " + last } def printDelim(delim) { println first + delim + last } def getFullName() { return first + " " + last } def getTotal(delim) { return first + delim + last } }
def name = new Name(first:"Paul", last:"Woods")
name.print()
Optional – Parenthesis 2
One or more arguments and not referencing the return value – () optional class Name { def first, last def print() { println first + " " + last } def printDelim(delim) { println first + delim + last } def getFullName() { return first + " " + last } def getTotal(delim) { return first + delim + last } }
def name = new Name(first:"Paul", last:"Woods")
name.printDelim " "
Optional – Parenthesis 3Optional – Parenthesis 3
The method has a ‘get’ prefix, and no arguments. () optional class Name { def first, last def print() { println first + " " + last } def printDelim(delim) { println first + delim + last } def getFullName() { return first + " " + last } def getTotal(delim) { return first + delim + last } }
def name = new Name(first:"Paul", last:"Woods")
println name.fullName
Optional – Parenthesis 4Optional – Parenthesis 4
method has ‘get’ and client has 1 or more arguments – () mandatory
class Name { def first, last def print() { println first + " " + last } def printDelim(delim) { println first + delim + last } def getFullName() { return first + " " + last } def getTotal(delim) { return first + delim + last } }
def name = new Name(first:"Paul", last:"Woods")
println name.getTotal(",")
Optional – semicolons
Semicolons are almost always optionalMust be used if multiple statements on a
single line.
def a = 1 def b = 2 println a println b println a; println b
Optional – returns – 1
Returns are optional when the value to be returned is the last line of the method. def sum(a, b) { a + b }
def sub(a, b) { def total = a + b total }
Optional – returns – 2
Returns are optional when the method is a if/else method. The value to be returned is the last line of each block.
def choose(a, b, c) { if(a > 0) { b } else if(a < 0) { c } else { 0 } }
println " 1 : " + choose( 1, 10, 20) println "-1 : " + choose(-1, 10, 20) println " 0 : " + choose( 0, 10, 20)
Optional – returns – 3
PowerAssert
Power Assert – in a failed assert statement, groovy shows you the values of the objects.
def map = [a : [ b : [ c : 2 ] ] ]
assert 3 == map.a.b.c | | | | | | | | | 2 | | | {c=2} | | {b={c=2}} | {a={b={c=2}}} false
PowerAssert - gotcha
PowerAssert Gotcha – whitespace
def a = "a"def b = "a\r\n"assert a == b
Assertion failed: assert a == b | | | a | a false
May not tell you about whitespace
Get the current groovy Version
import org.codehaus.groovy.runtime.InvokerHelper println InvokerHelper.version
Groovy
A Dynamic scripting language similar to the Java language
Executes on the JVM (1.5 and 1.6)Can be used stand-alone, or can be added to
a Java application.
Download and Install
http://groovy.codehaus.orgDownload .zipExtract to c:\toolsSet groovy_home = c:\tools\groovy-1.7.3Add to your path: %groovy_home%\bin
http://groovyconsole.appspot.com