Groovy: v 1.0

This commit is contained in:
Roberto Perez 2013-08-17 12:44:19 -05:00
parent 12b39c739f
commit 655ef1d66f

View File

@ -2,7 +2,7 @@
language: Groovy
filename: learngroovy.groovy
contributors:
- ["Roberto Perez Alcolea", "http://github.com/rpalcolea"]
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
filename: learngroovy.groovy
---
@ -182,6 +182,179 @@ for ( e in map ) {
x += e.value
}
/*
Operators
Operator Overloading for a list of the common operators that Groovy supports: http://groovy.codehaus.org/Operator+Overloading
Helpful groovy operators
*/
//Spread operator: invoke an action on all items of an aggregate object.
def technologies = ['Groovy','Grails','Gradle']
technologies*.toUpperCase() //equivalent to: technologies.collect { it?.toUpperCase() }
//Safe navigation operator: used to avoid a NullPointerException.
def user = User.get(1)
def username = user?.username
/*
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.
More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition
*/
//Example:
def clos = { println "Hello World!" }
println "Executing the Closure:"
clos()
//Passing parameters to a closure
def sum = { a, b -> println a+b }
sum(2,4)
//Closures may refer to variables not listed in their parameter list.
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)
//If you have a Closure that takes a single argument, you may omit the parameter definition of the Closure
def clos = { print it }
clos( "hi" )
/*
Groovy can memorize closure results:
More info at:
http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html
/*
def cl = {a, b ->
sleep(3000) // simulate some time consuming processing
a + b
}
mem = cl.memoize()
def callClosure(a, b) {
def start = System.currentTimeMillis()
mem(a, b)
println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."
}
callClosure(1, 2)
callClosure(1, 2)
callClosure(2, 3)
callClosure(2, 3)
callClosure(3, 4)
callClosure(3, 4)
callClosure(1, 2)
callClosure(2, 3)
callClosure(3, 4)
/*
Expando
The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class
Reference: http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
*/
def user = new Expando(name:"Roberto")
assert 'Roberto' == user.name
user.lastName = 'Pérez'
assert 'Pérez' == user.lastName
user.showInfo = { out ->
out << "Name: $name"
out << ", Last name: $lastName"
}
def sw = new StringWriter()
println user.showInfo(sw)
/*
Metaprogramming (MOP)
*/
//Using ExpandoMetaClass to add behaviour
String.metaClass.testAdd = {
println "we added this"
}
String x = "test"
x?.testAdd()
//Intercepting method calls
class Test implements GroovyInterceptable {
def sum(Integer x, Integer y) { x + y }
def invokeMethod(String name, args) {
System.out.println "Invoke method $name with args: $args"
}
}
def test = new Test()
test?.sum(2,3)
test?.multiply(2,3)
//Groovy supports propertyMissing for dealing with property resolution attempts.
class Foo {
def propertyMissing(String name) { name }
}
def f = new Foo()
assertEquals "boo", f.boo
/*
TypeChecked and CompileStatic
Groovy, by nature, is and will always be a dynamic language but it supports typechecked and compilestatic
More info: http://www.infoq.com/articles/new-groovy-20
*/
//TypeChecked
import groovy.transform.TypeChecked
void testMethod() {}
@TypeChecked
void test() {
testMeethod()
def name = "Roberto"
println naameee
}
//Another example:
import groovy.transform.TypeChecked
@TypeChecked
Integer test() {
Integer num = "1"
Integer[] numbers = [1,2,3,4]
Date date = numbers[1]
return "Test"
}
//CompileStatic example:
import groovy.transform.CompileStatic
@CompileStatic
int sum(int x, int y) {
x + y
}
assert sum(2,5) == 7
```
## Further resources