SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler offline
Groovy Overview



It is Java as it should be. Easy and intuitive, it
offers new features unknown to its parent yet,
and come up with those benefits that form the
basis of the DSLs

Giancarlo Frison
Groovy is a super vision of Java. It can leverage Java’s enterprise
capabilities but also has closures and dynamic typing, without all
ceremonial syntax needed in Java


●   Introduction
●   Data types
●   Language features
●   Closures
●   Meta programming
What is Groovy?
Introduction

 Groovy = Java – boiler plate code
   + mostly dynamic typing
   + closures
   + domain specific languages
Groovy Overview
●   Fully Object oriented         ●   Gpath expressions
●   Closures: reusable and        ●   Grep and switch
    assignable piece of code      ●   Builders (XML, Json, Swing,
●   Groovy Beans                      Ant, Tests)
●   Collection Literals (lists,   ●   Additional operators (? Null
    maps, ranges, regular             safe)
    expressions)                  ●   Default and named
●   Meta programming (MOP,            arguments
    Expando, AST                  ●   String enhances
    transformations,              ●   Osgi
    Mixins/Categories)
Frameworks
●   Grails Web framework inspired by Ruby on Rails
●   Gradle The next generation build system
●   Griffon Desktop framework inspired by Grails
●   Grape Add dependencies to your classpath
●   Gorm Grails ORM persistance framework
●   Gpars Concurrency/parallelism library
Less tedious syntax
A better Java…
…a better Java…
…a better Java…
…a better Java…
…a better Java…
…a better Java…
…a better Java…
…a better Java.
Better JavaBeans…
…a better JavaBeans…
…a better JavaBeans.
Data Types
GStrings
●   Multi-line strings            ●   Ranges
def tt = '''                      assert fullname[0..5] == name
    She sells, sea shells
    By the sea shore''‘
                                  ●   Comparison operators
                                  a==b    a +-* b
●   String interpolation          a<=>b   a[]
def fullname = “$name $surname”

                                  ●   Groovy-gdk
●   Regexs                        http://groovy.codehaus.
assert'-36'==~ ‘/^[+-]?d+$/’     org/groovy-
                                  jdk/java/lang/String.html
Collections
●   Literal syntax                ●   Overloading operators
list = [3,new Date(),’Jan']       list << new Date()
assert list + list == list * 2
                                  ●   Loop closures
                                  map.each{key, value ->
                                      println “$key : $value”
●   Maps                          }
map = [a:1,b:2]
assert map['a']==1 && map.b ==2   ●   …loop closures
                                  each, every, collect, any,
                                  inject, find, findAll,upto,
●   Ranges                        downto, times, grep,
                                  reverseEach, eachMatch,
def ls = ‘a'..'z‘,nums = 0..<10
                                  eachWithIndex, eachLine
assert ls.size+nums.size == 36    eachFile, eachFileMatch…
Math operations
●   No more :
BigDecimal.divide(BigDecimal right, <scale>,
    BigDecimal.ROUND_HALF_UP)


●   Instead
assert 1/2 == new java.math.BigDecimal("0.5")
Dates
use ( groovy.time.TimeCategory ) {
    println 1.minute.from.now
    println 10.hours.ago
    println new Date() - 3.months


    def duration = date1 - date2
    println "days: ${duration.days}, Hours: ${duration.hours}"
}
Language Features
Improved Switch
●  It can handle any kind of value
switch (x) {
   case 'James':
    break
   case 18..65:
    break
   case ~/Gw?+e/:
    break
   case Date:
    break
   case ['John', 'Ringo', 'Paul', 'George']:
    break
   default:
}
Groovy Truth
●   Any expression could be used and evaluated whereas
    Java requires a boolean.
●   Number 0                 return false
●   Empty string, lists, maps, matchers return false
●   Null objects             return false
●   Of course… boolean false        return false
Null Object Pattern
●   Null-safe version of Java's '.' operator

people << new Person(name:'Harry')

biggestSalary = people.collect{ p -> p.job?.salary }.max()

println biggestSalary
Named arguments
send(String from,   String to, String subject, String body) {
  println "sender   ${from}"
  println "sender   ${to}"
  println "sender   ${subject}"
  println "sender   ${body}"
}




send from:"john@example.com",
     to:"mike@example.com",
     subject:"greetings",
     body:"Hello Goodbye"
Multiple assignments
def (a, b, c) = [10, 20, 'foo']
assert a == 10 && b == 20 && c == 'foo‘




def geocode(String location) {
    // implementation returns [48.824068, 2.531733]
}
def (lat, long) = geocode(“Bassano del Grappa, Italia")
GPath
●   expression language integrated into Groovy which allows
    parts of nested structured data to be identified.
    ●   a.b.c -> for XML, yields all the <c> elements inside <b> inside
        <a>
def feed = new XmlSlurper().parse('http://gfrison.com/rss')
println feed.channel.item[0].title




    ●   a.b.c -> all POJOs, yields the <c> properties for all the <b>
        properties of <a> (sort of like a.getB().getC() in JavaBeans)
Closures
Closures
●   Treats data structures and operations as Objects
def clos = { println "hello!" }
clos()


●   Closures as method arguments
def houston = {doit ->
    (10..1).each{ count->
        doit(count)
    }
}
houston{ println it }
Closure delegate
●   Groovy has 3 variables inside each closure for defining
    different classes in his scope:
    ●   this: As in Java it refers to the closure itself.
    ●   owner: Enclosing object of the closure.
    ●   delegate: The same of the owner, but it can be replaced
●   When a closure encounters a method call that it cannot
    handle itself, it automatically relays the invocation to its
    owner object. If this fails, it relays the invocation to its
    delegate.
Closures for better design…
…more better design.
Meta Object Programming
Groovy MOP
●   Runtime            ●   Compile-time
●   ExpandoMetaClass   ●   AST Transformations
●   Closures
●   Categories
ExpandoMetaClass
●   Allow to dynamically add methods, properties…

String.metaClass.swapCase = {->
      def sb = new StringBuffer()
      delegate.each {
           sb << (Character.isUpperCase(it as char) ?
Character.toLowerCase(it as char) :
                    Character.toUpperCase(it as char))
      }
      sb.toString()
}


println "hELLO wORLD".swapCase()
Expando
●   It is a container for everything added by developer

def bean = new Expando( name:"James", location:"London", id:123 )
assert "James" == bean.name
assert 123     == bean.id
Categories
●  Add functionalities to classes to make them more usable
class StringCategory {
    static String lower(String string) {
        return string.toLowerCase()
    }
}
use (StringCategory) {
    assert "test" == "TeSt".lower()
}


use (groovy.time.TimeCategory ) {
    println 1.minute.from.now
    println 10.hours.ago
    println new Date() - 3.months
}
AST Examples
●   Grape
@Grab('org.mortbay.jetty:jetty-embedded:6.1.0')
def server = new Server(8080)
println "Starting Jetty, press Ctrl+C to stop."
server.start()
●   Slf4j
@Slf4j
class HelloWorld {
    def logHello() {
        log.info 'Hello World'
    }
}
AST Transformations
●   compile-time metaprogramming capabilities allowing
    powerful flexibility at the language level, without a
    runtime performance penalty.
●   Global transformations adding a jar
●   Local transformations by annotating code elements:
@Immutable @Delegate @Log @Field @PackageScope @AutoClone
@AutoExternalizable @ThreadInterrupt @TimedInterrupt
@ConditionalInterrupt @ToString @EqualsAndHashCode
@TupleConstructor @Canonical @InheritConstructors @WithReadLock
@WithWriteLock @ListenerList @Singleton @Lazy @Newify @Category
@Mixin @PackageScope @Grab @Bindable @Vetoable
…and Happy coding!




                    Questions?


Giancarlo Frison - gfrison.com

Mais conteúdo relacionado

Mais procurados

20110514 mongo dbチューニング
20110514 mongo dbチューニング20110514 mongo dbチューニング
20110514 mongo dbチューニングYuichi Matsuo
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDBScott Hernandez
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Michaël Figuière
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redisDvir Volk
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Groupsiculars
 
glance replicator
glance replicatorglance replicator
glance replicatoririx_jp
 
What's New in the PHP Driver
What's New in the PHP DriverWhat's New in the PHP Driver
What's New in the PHP DriverMongoDB
 
MongoDB: Optimising for Performance, Scale & Analytics
MongoDB: Optimising for Performance, Scale & AnalyticsMongoDB: Optimising for Performance, Scale & Analytics
MongoDB: Optimising for Performance, Scale & AnalyticsServer Density
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceAlexander Gladysh
 

Mais procurados (20)

20110514 mongo dbチューニング
20110514 mongo dbチューニング20110514 mongo dbチューニング
20110514 mongo dbチューニング
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Group
 
glance replicator
glance replicatorglance replicator
glance replicator
 
What's New in the PHP Driver
What's New in the PHP DriverWhat's New in the PHP Driver
What's New in the PHP Driver
 
MongoDB: Optimising for Performance, Scale & Analytics
MongoDB: Optimising for Performance, Scale & AnalyticsMongoDB: Optimising for Performance, Scale & Analytics
MongoDB: Optimising for Performance, Scale & Analytics
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
Declarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing ExperienceDeclarative Internal DSLs in Lua: A Game Changing Experience
Declarative Internal DSLs in Lua: A Game Changing Experience
 

Semelhante a Groovy.pptx

Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshopadam1davis
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshopAdam Davis
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Writing Groovy DSLs
Writing Groovy DSLsWriting Groovy DSLs
Writing Groovy DSLsadam1davis
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Bozhidar Batsov
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Throughniklal
 

Semelhante a Groovy.pptx (20)

Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshop
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
 
Groovy
GroovyGroovy
Groovy
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Groovy to gradle
Groovy to gradleGroovy to gradle
Groovy to gradle
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Writing Groovy DSLs
Writing Groovy DSLsWriting Groovy DSLs
Writing Groovy DSLs
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Through
 
Groovy!
Groovy!Groovy!
Groovy!
 

Groovy.pptx

  • 1. Groovy Overview It is Java as it should be. Easy and intuitive, it offers new features unknown to its parent yet, and come up with those benefits that form the basis of the DSLs Giancarlo Frison
  • 2. Groovy is a super vision of Java. It can leverage Java’s enterprise capabilities but also has closures and dynamic typing, without all ceremonial syntax needed in Java ● Introduction ● Data types ● Language features ● Closures ● Meta programming
  • 4. Introduction Groovy = Java – boiler plate code + mostly dynamic typing + closures + domain specific languages
  • 5. Groovy Overview ● Fully Object oriented ● Gpath expressions ● Closures: reusable and ● Grep and switch assignable piece of code ● Builders (XML, Json, Swing, ● Groovy Beans Ant, Tests) ● Collection Literals (lists, ● Additional operators (? Null maps, ranges, regular safe) expressions) ● Default and named ● Meta programming (MOP, arguments Expando, AST ● String enhances transformations, ● Osgi Mixins/Categories)
  • 6. Frameworks ● Grails Web framework inspired by Ruby on Rails ● Gradle The next generation build system ● Griffon Desktop framework inspired by Grails ● Grape Add dependencies to your classpath ● Gorm Grails ORM persistance framework ● Gpars Concurrency/parallelism library
  • 20. GStrings ● Multi-line strings ● Ranges def tt = ''' assert fullname[0..5] == name She sells, sea shells By the sea shore''‘ ● Comparison operators a==b a +-* b ● String interpolation a<=>b a[] def fullname = “$name $surname” ● Groovy-gdk ● Regexs http://groovy.codehaus. assert'-36'==~ ‘/^[+-]?d+$/’ org/groovy- jdk/java/lang/String.html
  • 21. Collections ● Literal syntax ● Overloading operators list = [3,new Date(),’Jan'] list << new Date() assert list + list == list * 2 ● Loop closures map.each{key, value -> println “$key : $value” ● Maps } map = [a:1,b:2] assert map['a']==1 && map.b ==2 ● …loop closures each, every, collect, any, inject, find, findAll,upto, ● Ranges downto, times, grep, reverseEach, eachMatch, def ls = ‘a'..'z‘,nums = 0..<10 eachWithIndex, eachLine assert ls.size+nums.size == 36 eachFile, eachFileMatch…
  • 22. Math operations ● No more : BigDecimal.divide(BigDecimal right, <scale>, BigDecimal.ROUND_HALF_UP) ● Instead assert 1/2 == new java.math.BigDecimal("0.5")
  • 23. Dates use ( groovy.time.TimeCategory ) { println 1.minute.from.now println 10.hours.ago println new Date() - 3.months def duration = date1 - date2 println "days: ${duration.days}, Hours: ${duration.hours}" }
  • 25. Improved Switch ● It can handle any kind of value switch (x) { case 'James': break case 18..65: break case ~/Gw?+e/: break case Date: break case ['John', 'Ringo', 'Paul', 'George']: break default: }
  • 26. Groovy Truth ● Any expression could be used and evaluated whereas Java requires a boolean. ● Number 0 return false ● Empty string, lists, maps, matchers return false ● Null objects return false ● Of course… boolean false return false
  • 27. Null Object Pattern ● Null-safe version of Java's '.' operator people << new Person(name:'Harry') biggestSalary = people.collect{ p -> p.job?.salary }.max() println biggestSalary
  • 28. Named arguments send(String from, String to, String subject, String body) { println "sender ${from}" println "sender ${to}" println "sender ${subject}" println "sender ${body}" } send from:"john@example.com", to:"mike@example.com", subject:"greetings", body:"Hello Goodbye"
  • 29. Multiple assignments def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo‘ def geocode(String location) { // implementation returns [48.824068, 2.531733] } def (lat, long) = geocode(“Bassano del Grappa, Italia")
  • 30. GPath ● expression language integrated into Groovy which allows parts of nested structured data to be identified. ● a.b.c -> for XML, yields all the <c> elements inside <b> inside <a> def feed = new XmlSlurper().parse('http://gfrison.com/rss') println feed.channel.item[0].title ● a.b.c -> all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a.getB().getC() in JavaBeans)
  • 32. Closures ● Treats data structures and operations as Objects def clos = { println "hello!" } clos() ● Closures as method arguments def houston = {doit -> (10..1).each{ count-> doit(count) } } houston{ println it }
  • 33. Closure delegate ● Groovy has 3 variables inside each closure for defining different classes in his scope: ● this: As in Java it refers to the closure itself. ● owner: Enclosing object of the closure. ● delegate: The same of the owner, but it can be replaced ● When a closure encounters a method call that it cannot handle itself, it automatically relays the invocation to its owner object. If this fails, it relays the invocation to its delegate.
  • 34. Closures for better design…
  • 37. Groovy MOP ● Runtime ● Compile-time ● ExpandoMetaClass ● AST Transformations ● Closures ● Categories
  • 38. ExpandoMetaClass ● Allow to dynamically add methods, properties… String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() } println "hELLO wORLD".swapCase()
  • 39. Expando ● It is a container for everything added by developer def bean = new Expando( name:"James", location:"London", id:123 ) assert "James" == bean.name assert 123 == bean.id
  • 40. Categories ● Add functionalities to classes to make them more usable class StringCategory { static String lower(String string) { return string.toLowerCase() } } use (StringCategory) { assert "test" == "TeSt".lower() } use (groovy.time.TimeCategory ) { println 1.minute.from.now println 10.hours.ago println new Date() - 3.months }
  • 41. AST Examples ● Grape @Grab('org.mortbay.jetty:jetty-embedded:6.1.0') def server = new Server(8080) println "Starting Jetty, press Ctrl+C to stop." server.start() ● Slf4j @Slf4j class HelloWorld { def logHello() { log.info 'Hello World' } }
  • 42. AST Transformations ● compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty. ● Global transformations adding a jar ● Local transformations by annotating code elements: @Immutable @Delegate @Log @Field @PackageScope @AutoClone @AutoExternalizable @ThreadInterrupt @TimedInterrupt @ConditionalInterrupt @ToString @EqualsAndHashCode @TupleConstructor @Canonical @InheritConstructors @WithReadLock @WithWriteLock @ListenerList @Singleton @Lazy @Newify @Category @Mixin @PackageScope @Grab @Bindable @Vetoable
  • 43. …and Happy coding! Questions? Giancarlo Frison - gfrison.com