SlideShare a Scribd company logo
1 of 54
Download to read offline
Introduction to Groovy




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
Agenda
    • What is Groovy
    • From Java to Groovy
    • Java-like features
    • Not-Java features
    • Unique features
    • Eclipse & Groovy




         Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
2
What is Groovy?




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
http://www.flickr.com/photos/teagrrl/78941282/




    Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
4
From Java to Groovy




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
HelloWorld in Java
    public class HelloWorld {
       String name;

        public void setName(String name)
        { this.name = name; }
        public String getName(){ return name; }

        public String greet()
        { return quot;Hello quot;+ name; }

        public static void main(String args[]){
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setName(quot;Groovyquot;);
           System.out.println( helloWorld.greet() );
        }
    }




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
6
HelloWorld in Groovy
    public class HelloWorld {
       String name;

        public void setName(String name)
        { this.name = name; }
        public String getName(){ return name; }

        public String greet()
        { return quot;Hello quot;+ name; }

        public static void main(String args[]){
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setName(quot;Groovyquot;);
           System.out.println( helloWorld.greet() );
        }
    }




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
7
Step 1: Let’s get rid of the noise
    public class HelloWorld {
       String name;

        public void setName(String name)
        { this.name = name; }
        public String getName(){ return name; }

        public String greet()
        { return quot;Hello quot;+ name; }

        public static void main(String args[]){
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setName(quot;Groovyquot;);
           System.out.println( helloWorld.greet() );
        }
    }




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
8
Step 1 - Results
    class HelloWorld {
       String name

        void setName(String name)
        { this.name = name }
        String getName(){ return name }

        String greet()
        { return quot;Hello quot;+ name }

        static void main(String args[]){
           HelloWorld helloWorld = new HelloWorld()
           helloWorld.setName(quot;Groovyquot;)
           System.out.println( helloWorld.greet() )
        }
    }




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
9
Step 2: let’s get rid of boilerplate
     class HelloWorld {
        String name

         void setName(String name)
         { this.name = name }
         String getName(){ return name }

         String greet()
         { return quot;Hello quot;+ name }

         static void main(String args[]){
                                 args[]
            HelloWorld helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            System.out.println( helloWorld.greet() )
            System.out.
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
10
Step 2 - Results
     class HelloWorld {
        String name

         String greet()
         { return quot;Hello quot;+ name }

         static void main( args ){
            HelloWorld helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
11
Step 3: Introduce dynamic types
     class HelloWorld {
        String name

         String greet()
         { return quot;Hello quot;+ name }

         static void main( args ){
            HelloWorld helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
12
Step 3 - Results
     class HelloWorld {
        String name

         def greet()
         { return quot;Hello quot;+ name }

         static def main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
13
Step 4: Use variable interpolation
     class HelloWorld {
        String name

         def greet(){ return quot;Hello quot;+ name }

         static def main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
14
Step 4 - Results
     class HelloWorld {
        String name

         def greet(){ return quot;Hello ${name}quot; }

         static def main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
15
Step 5: Let’s get rid of more keywords
     class HelloWorld {
        String name

         def greet(){ return quot;Hello ${name}quot; }

         static def main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
16
Step 5 - Results
     class HelloWorld {
        String name

         def greet(){ quot;Hello ${name}quot; }

         static main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
17
Step 6: POJOs on steroids
     class HelloWorld {
        String name

         def greet(){ quot;Hello ${name}quot; }

         static main( args ){
            def helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
18
Step 6 - Results
     class HelloWorld {
        String name

         def greet(){ quot;Hello ${name}quot; }

         static main( args ){
            def helloWorld = new HelloWorld(name:quot;Groovyquot;)
            // helloWorld.setName(quot;Groovyquot;)
            // helloWorld.name = quot;Groovyquot;
            // helloWorld[quot;namequot;] = quot;Groovyquot;
            println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
19
Step 7: Groovy supports scripts
     class HelloWorld {
        String name

         def greet(){ quot;Hello ${name}quot; }

         static main( args ){
            def helloWorld = new HelloWorld(name:quot;Groovyquot;)
            println helloWorld.greet()
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
20
Step 7 - Results
     class HelloWorld {
        String name
        def greet() { quot;Hello $namequot; }
     }

     def helloWorld = new HelloWorld(name:quot;Groovyquot;)
     println helloWorld.greet()




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
21
We came from here…
     public class HelloWorld {
        String name;

         public void setName(String name)
         { this.name = name; }
         public String getName(){ return name; }

         public String greet()
         { return quot;Hello quot;+ name; }

         public static void main(String args[]){
            HelloWorld helloWorld = new HelloWorld()
            helloWorld.setName(quot;Groovyquot;)
            System.err.println( helloWorld.greet() )
         }
     }




            Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
22
… to here
     class HelloWorld {
        String name
        def greet() { quot;Hello $namequot; }
     }

     def helloWorld = new HelloWorld(name:quot;Groovyquot;)
     println helloWorld.greet()




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
23
Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
24
Java-like Features
        Close to home




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
Java -like features
     • A Java class is a Groovy class, a Groovy class is a
       Java class
     • Full JDK5 support: annotations, generics, varargs,
       enums, enhanced for loop (this requires JRE5)
     • 98% of Java code is valid Groovy code




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
26
Varargs in action
     class Calculator {
        def addAllGroovy( Object[] args ){
           int total = 0
           for( i in args ) { total += i }
           total
        }
        def addAllJava( int... args ){
           int total = 0
           for( i in args ) { total += i }
           total
        }
     }

     Calculator c = new Calculator()
     assert c.addAllGroovy(1,2,3,4,5) == 15
     assert c.addAllJava(1,2,3,4,5) == 15




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
27
Scott Davis' 1st mantra:
                      Java is Groovy, Groovy is Java




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
28
Not-Java Features
        Explore the Neighborhood




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
Assorted goodies
     • Default parameter values as in PHP
     • Named parameters as in Ruby (reuse the Map trick of
       default POGO constructor)
     • Operator overloading, using a naming convention, for
       example


                      +                       plus()
                      []                      getAt() / putAt()
                      <<                      leftShift()


          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
30
Closures
     • Closures can be seen as reusable blocks of code, you
       may have seen them in JavaScript and Ruby among
       other languages.
     • Closures substitute inner classes in almost all use
       cases.
     • Groovy allows type coercion of a Closure into a one-
       method interface
     • A closure will have a default parameter named it if you
       do not define one.




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
31
Examples of closures
     def greet = { name -> println “Hello $name” }
     greet( “Groovy” )
     // prints Hello Groovy

     def greet = { println “Hello $it” }
     greet( “Groovy” )
     // prints Hello Groovy

     def iCanHaveTypedParametersToo = { int x, int y ->
        println “coordinates are ($x,$y)”
     }

     def myActionListener = { event ->
        // do something cool with event
     } as ActionListener




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
32
With closures comes currying
     • Currying is a programming technique that transforms a
       function into another while fixing one or more input
       values (think constants).




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
33
Currying in action
     // a closure with 3 parameters, the third one is optional
     // as it defines a default value
     def getSlope = { x, y, b = 0 ->
        println quot;x:${x} y:${y} b:${b}quot;
        (y - b) / x
     }

     assert 1 == getSlope( 2, 2 )
     def getSlopeX = getSlope.curry(5)
     assert 1 == getSlopeX(5)
     assert 0 == getSlopeX(2.5,2.5)
     // prints
     // x:2 y:2 b:0
     // x:5 y:5 b:0
     // x:5 y:2.5 b:2.5




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
34
Iterators everywhere
     • Like in Ruby you may use iterators in almost any
       context, Groovy will figure out what to do in each case
     • Iterators harness the power of closures, all iterators
       accept a closure as parameter.
     • Iterators relieve you of the burden of looping
       constructs




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
35
Iterators in action
     def printIt = { println it }
     // 3 ways to iterate from 1 to 5
     [1,2,3,4,5].each printIt
     1.upto 5, printIt
     (1..5).each printIt

     // compare to a regular loop
     for( i in [1,2,3,4,5] ) printIt(i)
     // same thing but use a Range
     for( i in (1..5) ) printIt(i)

     [1,2,3,4,5].eachWithIndex { v, i -> println quot;list[$i] => $vquot; }
     // list[0] => 1
     // list[1] => 2
     // list[2] => 3
     // list[3] => 4
     // list[4] => 5


           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
36
Scott Davis' 2nd mantra:
          Groovy is Java and Groovy is NOT Java




         Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
37
Unique Features
        Space out!




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
The as keyword
     • Used for “Groovy casting”, convert a value of typeA
       into a value of typeB
       def intarray = [1,2,3] as int[ ]


     • Used to coerce a closure into an implementation of
       single method interface.

     • Used to coerce a Map into an implementation of an
       interface, abstract and/or concrete class.

     • Used to create aliases on imports

          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
39
Some examples of as
     import javax.swing.table.DefaultTableCellRenderer as DTCR

     def myActionListener = { event ->
        // do something cool with event
     } as ActionListener

     def renderer = [
        getTableCellRendererComponent: { t, v, s, f, r, c ->
          // cool renderer code goes here
        }
     ] as DTCR

     //   note that this technique is like creating objects in
     //   JavaScript with JSON format
     //   it also circumvents the fact that Groovy can’t create
     //   inner classes (yet)




             Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
40
New operators
     • ?: (elvis) - a refinement over the ternary operator

     • ?. Safe dereference – navigate an object graph without
       worrying on NPEs

     • <=> (spaceship) – compares two values

     • * (spread) – “explode” the contents of a list or array

     • *. (spread-dot) – apply a method call to every element
       of a list or array

           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
41
Traversing object graphs
     • GPath is to objects what XPath is to XML.

     • *. and ?. come in handy in many situations

     • Because POGOs accept dot and bracket notation for
       property access its very easy to write GPath
       expressions.




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
42
Sample GPath expressions
     class Person {
        String name
        int id
     }

     def persons = [
        new Person( name: 'Duke', id: 1 ),
        [name: 'Tux', id: 2] as Person
     ]

     assert   [1,2] == persons.id
     assert   ['Duke','Tux'] == persons*.getName()
     assert   null == persons[2]?.name
     assert   'Duke' == persons[0].name ?: 'Groovy'
     assert   'Groovy' == persons[2]?.name ?: 'Groovy'




              Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
43
MetaProgramming

     • You can add methods and properties to any object at
       runtime.

     • You can intercept calls to method invocations and/or
       property access (similar to doing AOP but without the
       hassle).

     • This means Groovy offers a similar concept to Ruby’s
       open classes, Groovy even extends final classes as
       String and Integer with new methods (we call it GDK).


          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
44
A simple example using categories
     class Pouncer {
        static pounce( Integer self ){
           def s = “Boing!quot;
           1.upto(self-1) { s += quot; boing!quot; }
           s + quot;!quot;
        }
     }

     use( Pouncer ){
        assert 3.pounce() == “Boing! boing! boing!quot;
     }




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
45
Same example using MetaClasses
     Integer.metaClass.pounce << { ->
        def s = “Boing!quot;
        delegate.upto(delegate-1) { s += quot; boing!quot; }
        s + quot;!“
     }

     assert 3.pounce() == “Boing! boing! boing!quot;




           Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
46
More options in Groovy 1.6!

     • Compile time metaprogramming via AST
       transformations

     • Runtime mixins




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
47
Scott Davis says:
      Groovy is what the Java language would look like
           had it been written in the 21st century




         Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
48
Eclipse & Groovy




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
Eclipse Plugin
     • Allows you to edit, compile and run groovy scripts and
       classes.
     • Syntax coloring
     • Autocompletion
     • Groovy nature
     • Great support from Eclipse +3.2 series




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
50
How to install
     1. Go to Help -> Software Updates -> Find and Install
     2. Configure a new update site
       http://dist.codehaus.org/groovy/distributions/update/
     3. Follow the wizard instructions
     4. Restart Eclipse. You are now ready to start
        Groovying!




          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
51
Resources
     • Groovy Language, guides, examples
        http://groovy.codehaus.org
     • Groovy Eclipse Plugin
        http://groovy.codehaus.org/Eclipse+Plugin
     • Groovy Related News
        http://aboutgroovy.com
        http://groovyblogs.org
        http://groovy.dzone.com
     • My Groovy/Java/Swing blog
        http://jroller.com/aalmiray
        http://twitter.com/aalmiray

          Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0
52
Q&A




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
Thank you!




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009

More Related Content

Similar to Eclipsecon09 Introduction To Groovy

Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle GroovyDeepak Bhagat
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyAndres Almiray
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovymanishkp84
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 
GeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyGeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyIván López Martín
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Session inaugurale du Groovy User Group Paris
Session inaugurale du Groovy User Group ParisSession inaugurale du Groovy User Group Paris
Session inaugurale du Groovy User Group ParisGuillaume Laforge
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyIván López Martín
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developersPuneet Behl
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaJohn Leach
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyAndres Almiray
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemKostas Saidis
 
Corinna-2023.pptx
Corinna-2023.pptxCorinna-2023.pptx
Corinna-2023.pptxCurtis Poe
 

Similar to Eclipsecon09 Introduction To Groovy (20)

Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
Presentatie - Introductie in Groovy
Presentatie - Introductie in GroovyPresentatie - Introductie in Groovy
Presentatie - Introductie in Groovy
 
GeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyGeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with Groovy
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Session inaugurale du Groovy User Group Paris
Session inaugurale du Groovy User Group ParisSession inaugurale du Groovy User Group Paris
Session inaugurale du Groovy User Group Paris
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with Groovy
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 
Groovy!
Groovy!Groovy!
Groovy!
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
Corinna-2023.pptx
Corinna-2023.pptxCorinna-2023.pptx
Corinna-2023.pptx
 

More from Andres Almiray

Creando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abiertoCreando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abiertoAndres Almiray
 
Liberando a produccion con confianza
Liberando a produccion con confianzaLiberando a produccion con confianza
Liberando a produccion con confianzaAndres Almiray
 
Liberando a produccion con confidencia
Liberando a produccion con confidenciaLiberando a produccion con confidencia
Liberando a produccion con confidenciaAndres Almiray
 
OracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java DevelopersOracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java DevelopersAndres Almiray
 
Softcon.ph - Maven Puzzlers
Softcon.ph - Maven PuzzlersSoftcon.ph - Maven Puzzlers
Softcon.ph - Maven PuzzlersAndres Almiray
 
Oracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java DevelopersOracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java DevelopersAndres Almiray
 
JReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of lightJReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of lightAndres Almiray
 
Building modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and LayrryBuilding modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and LayrryAndres Almiray
 
Going Reactive with g rpc
Going Reactive with g rpcGoing Reactive with g rpc
Going Reactive with g rpcAndres Almiray
 
Building modular applications with JPMS and Layrry
Building modular applications with JPMS and LayrryBuilding modular applications with JPMS and Layrry
Building modular applications with JPMS and LayrryAndres Almiray
 
Taking Micronaut out for a spin
Taking Micronaut out for a spinTaking Micronaut out for a spin
Taking Micronaut out for a spinAndres Almiray
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouAndres Almiray
 
What I wish I knew about Maven years ago
What I wish I knew about Maven years agoWhat I wish I knew about Maven years ago
What I wish I knew about Maven years agoAndres Almiray
 
What I wish I knew about maven years ago
What I wish I knew about maven years agoWhat I wish I knew about maven years ago
What I wish I knew about maven years agoAndres Almiray
 
The impact of sci fi in tech
The impact of sci fi in techThe impact of sci fi in tech
The impact of sci fi in techAndres Almiray
 
Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019Andres Almiray
 
Creating Better Builds with Gradle
Creating Better Builds with GradleCreating Better Builds with Gradle
Creating Better Builds with GradleAndres Almiray
 
Interacting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with GradleInteracting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with GradleAndres Almiray
 

More from Andres Almiray (20)

Creando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abiertoCreando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abierto
 
Liberando a produccion con confianza
Liberando a produccion con confianzaLiberando a produccion con confianza
Liberando a produccion con confianza
 
Liberando a produccion con confidencia
Liberando a produccion con confidenciaLiberando a produccion con confidencia
Liberando a produccion con confidencia
 
OracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java DevelopersOracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java Developers
 
Softcon.ph - Maven Puzzlers
Softcon.ph - Maven PuzzlersSoftcon.ph - Maven Puzzlers
Softcon.ph - Maven Puzzlers
 
Maven Puzzlers
Maven PuzzlersMaven Puzzlers
Maven Puzzlers
 
Oracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java DevelopersOracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java Developers
 
JReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of lightJReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of light
 
Building modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and LayrryBuilding modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and Layrry
 
Going Reactive with g rpc
Going Reactive with g rpcGoing Reactive with g rpc
Going Reactive with g rpc
 
Building modular applications with JPMS and Layrry
Building modular applications with JPMS and LayrryBuilding modular applications with JPMS and Layrry
Building modular applications with JPMS and Layrry
 
Taking Micronaut out for a spin
Taking Micronaut out for a spinTaking Micronaut out for a spin
Taking Micronaut out for a spin
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and You
 
What I wish I knew about Maven years ago
What I wish I knew about Maven years agoWhat I wish I knew about Maven years ago
What I wish I knew about Maven years ago
 
What I wish I knew about maven years ago
What I wish I knew about maven years agoWhat I wish I knew about maven years ago
What I wish I knew about maven years ago
 
The impact of sci fi in tech
The impact of sci fi in techThe impact of sci fi in tech
The impact of sci fi in tech
 
Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019
 
Creating Better Builds with Gradle
Creating Better Builds with GradleCreating Better Builds with Gradle
Creating Better Builds with Gradle
 
Interacting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with GradleInteracting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with Gradle
 
Gradle ex-machina
Gradle ex-machinaGradle ex-machina
Gradle ex-machina
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Eclipsecon09 Introduction To Groovy

  • 1. Introduction to Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 2. Agenda • What is Groovy • From Java to Groovy • Java-like features • Not-Java features • Unique features • Eclipse & Groovy Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 2
  • 3. What is Groovy? © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 4. http://www.flickr.com/photos/teagrrl/78941282/ Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 4
  • 5. From Java to Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 6. HelloWorld in Java public class HelloWorld { String name; public void setName(String name) { this.name = name; } public String getName(){ return name; } public String greet() { return quot;Hello quot;+ name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld(); helloWorld.setName(quot;Groovyquot;); System.out.println( helloWorld.greet() ); } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 6
  • 7. HelloWorld in Groovy public class HelloWorld { String name; public void setName(String name) { this.name = name; } public String getName(){ return name; } public String greet() { return quot;Hello quot;+ name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld(); helloWorld.setName(quot;Groovyquot;); System.out.println( helloWorld.greet() ); } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 7
  • 8. Step 1: Let’s get rid of the noise public class HelloWorld { String name; public void setName(String name) { this.name = name; } public String getName(){ return name; } public String greet() { return quot;Hello quot;+ name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld(); helloWorld.setName(quot;Groovyquot;); System.out.println( helloWorld.greet() ); } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 8
  • 9. Step 1 - Results class HelloWorld { String name void setName(String name) { this.name = name } String getName(){ return name } String greet() { return quot;Hello quot;+ name } static void main(String args[]){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) System.out.println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 9
  • 10. Step 2: let’s get rid of boilerplate class HelloWorld { String name void setName(String name) { this.name = name } String getName(){ return name } String greet() { return quot;Hello quot;+ name } static void main(String args[]){ args[] HelloWorld helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) System.out.println( helloWorld.greet() ) System.out. } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 10
  • 11. Step 2 - Results class HelloWorld { String name String greet() { return quot;Hello quot;+ name } static void main( args ){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 11
  • 12. Step 3: Introduce dynamic types class HelloWorld { String name String greet() { return quot;Hello quot;+ name } static void main( args ){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 12
  • 13. Step 3 - Results class HelloWorld { String name def greet() { return quot;Hello quot;+ name } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 13
  • 14. Step 4: Use variable interpolation class HelloWorld { String name def greet(){ return quot;Hello quot;+ name } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 14
  • 15. Step 4 - Results class HelloWorld { String name def greet(){ return quot;Hello ${name}quot; } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 15
  • 16. Step 5: Let’s get rid of more keywords class HelloWorld { String name def greet(){ return quot;Hello ${name}quot; } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 16
  • 17. Step 5 - Results class HelloWorld { String name def greet(){ quot;Hello ${name}quot; } static main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 17
  • 18. Step 6: POJOs on steroids class HelloWorld { String name def greet(){ quot;Hello ${name}quot; } static main( args ){ def helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 18
  • 19. Step 6 - Results class HelloWorld { String name def greet(){ quot;Hello ${name}quot; } static main( args ){ def helloWorld = new HelloWorld(name:quot;Groovyquot;) // helloWorld.setName(quot;Groovyquot;) // helloWorld.name = quot;Groovyquot; // helloWorld[quot;namequot;] = quot;Groovyquot; println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 19
  • 20. Step 7: Groovy supports scripts class HelloWorld { String name def greet(){ quot;Hello ${name}quot; } static main( args ){ def helloWorld = new HelloWorld(name:quot;Groovyquot;) println helloWorld.greet() } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 20
  • 21. Step 7 - Results class HelloWorld { String name def greet() { quot;Hello $namequot; } } def helloWorld = new HelloWorld(name:quot;Groovyquot;) println helloWorld.greet() Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 21
  • 22. We came from here… public class HelloWorld { String name; public void setName(String name) { this.name = name; } public String getName(){ return name; } public String greet() { return quot;Hello quot;+ name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName(quot;Groovyquot;) System.err.println( helloWorld.greet() ) } } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 22
  • 23. … to here class HelloWorld { String name def greet() { quot;Hello $namequot; } } def helloWorld = new HelloWorld(name:quot;Groovyquot;) println helloWorld.greet() Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 23
  • 24. Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 24
  • 25. Java-like Features Close to home © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 26. Java -like features • A Java class is a Groovy class, a Groovy class is a Java class • Full JDK5 support: annotations, generics, varargs, enums, enhanced for loop (this requires JRE5) • 98% of Java code is valid Groovy code Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 26
  • 27. Varargs in action class Calculator { def addAllGroovy( Object[] args ){ int total = 0 for( i in args ) { total += i } total } def addAllJava( int... args ){ int total = 0 for( i in args ) { total += i } total } } Calculator c = new Calculator() assert c.addAllGroovy(1,2,3,4,5) == 15 assert c.addAllJava(1,2,3,4,5) == 15 Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 27
  • 28. Scott Davis' 1st mantra: Java is Groovy, Groovy is Java Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 28
  • 29. Not-Java Features Explore the Neighborhood © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 30. Assorted goodies • Default parameter values as in PHP • Named parameters as in Ruby (reuse the Map trick of default POGO constructor) • Operator overloading, using a naming convention, for example + plus() [] getAt() / putAt() << leftShift() Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 30
  • 31. Closures • Closures can be seen as reusable blocks of code, you may have seen them in JavaScript and Ruby among other languages. • Closures substitute inner classes in almost all use cases. • Groovy allows type coercion of a Closure into a one- method interface • A closure will have a default parameter named it if you do not define one. Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 31
  • 32. Examples of closures def greet = { name -> println “Hello $name” } greet( “Groovy” ) // prints Hello Groovy def greet = { println “Hello $it” } greet( “Groovy” ) // prints Hello Groovy def iCanHaveTypedParametersToo = { int x, int y -> println “coordinates are ($x,$y)” } def myActionListener = { event -> // do something cool with event } as ActionListener Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 32
  • 33. With closures comes currying • Currying is a programming technique that transforms a function into another while fixing one or more input values (think constants). Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 33
  • 34. Currying in action // a closure with 3 parameters, the third one is optional // as it defines a default value def getSlope = { x, y, b = 0 -> println quot;x:${x} y:${y} b:${b}quot; (y - b) / x } assert 1 == getSlope( 2, 2 ) def getSlopeX = getSlope.curry(5) assert 1 == getSlopeX(5) assert 0 == getSlopeX(2.5,2.5) // prints // x:2 y:2 b:0 // x:5 y:5 b:0 // x:5 y:2.5 b:2.5 Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 34
  • 35. Iterators everywhere • Like in Ruby you may use iterators in almost any context, Groovy will figure out what to do in each case • Iterators harness the power of closures, all iterators accept a closure as parameter. • Iterators relieve you of the burden of looping constructs Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 35
  • 36. Iterators in action def printIt = { println it } // 3 ways to iterate from 1 to 5 [1,2,3,4,5].each printIt 1.upto 5, printIt (1..5).each printIt // compare to a regular loop for( i in [1,2,3,4,5] ) printIt(i) // same thing but use a Range for( i in (1..5) ) printIt(i) [1,2,3,4,5].eachWithIndex { v, i -> println quot;list[$i] => $vquot; } // list[0] => 1 // list[1] => 2 // list[2] => 3 // list[3] => 4 // list[4] => 5 Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 36
  • 37. Scott Davis' 2nd mantra: Groovy is Java and Groovy is NOT Java Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 37
  • 38. Unique Features Space out! © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 39. The as keyword • Used for “Groovy casting”, convert a value of typeA into a value of typeB def intarray = [1,2,3] as int[ ] • Used to coerce a closure into an implementation of single method interface. • Used to coerce a Map into an implementation of an interface, abstract and/or concrete class. • Used to create aliases on imports Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 39
  • 40. Some examples of as import javax.swing.table.DefaultTableCellRenderer as DTCR def myActionListener = { event -> // do something cool with event } as ActionListener def renderer = [ getTableCellRendererComponent: { t, v, s, f, r, c -> // cool renderer code goes here } ] as DTCR // note that this technique is like creating objects in // JavaScript with JSON format // it also circumvents the fact that Groovy can’t create // inner classes (yet) Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 40
  • 41. New operators • ?: (elvis) - a refinement over the ternary operator • ?. Safe dereference – navigate an object graph without worrying on NPEs • <=> (spaceship) – compares two values • * (spread) – “explode” the contents of a list or array • *. (spread-dot) – apply a method call to every element of a list or array Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 41
  • 42. Traversing object graphs • GPath is to objects what XPath is to XML. • *. and ?. come in handy in many situations • Because POGOs accept dot and bracket notation for property access its very easy to write GPath expressions. Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 42
  • 43. Sample GPath expressions class Person { String name int id } def persons = [ new Person( name: 'Duke', id: 1 ), [name: 'Tux', id: 2] as Person ] assert [1,2] == persons.id assert ['Duke','Tux'] == persons*.getName() assert null == persons[2]?.name assert 'Duke' == persons[0].name ?: 'Groovy' assert 'Groovy' == persons[2]?.name ?: 'Groovy' Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 43
  • 44. MetaProgramming • You can add methods and properties to any object at runtime. • You can intercept calls to method invocations and/or property access (similar to doing AOP but without the hassle). • This means Groovy offers a similar concept to Ruby’s open classes, Groovy even extends final classes as String and Integer with new methods (we call it GDK). Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 44
  • 45. A simple example using categories class Pouncer { static pounce( Integer self ){ def s = “Boing!quot; 1.upto(self-1) { s += quot; boing!quot; } s + quot;!quot; } } use( Pouncer ){ assert 3.pounce() == “Boing! boing! boing!quot; } Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 45
  • 46. Same example using MetaClasses Integer.metaClass.pounce << { -> def s = “Boing!quot; delegate.upto(delegate-1) { s += quot; boing!quot; } s + quot;!“ } assert 3.pounce() == “Boing! boing! boing!quot; Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 46
  • 47. More options in Groovy 1.6! • Compile time metaprogramming via AST transformations • Runtime mixins Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 47
  • 48. Scott Davis says: Groovy is what the Java language would look like had it been written in the 21st century Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 48
  • 49. Eclipse & Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 50. Eclipse Plugin • Allows you to edit, compile and run groovy scripts and classes. • Syntax coloring • Autocompletion • Groovy nature • Great support from Eclipse +3.2 series Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 50
  • 51. How to install 1. Go to Help -> Software Updates -> Find and Install 2. Configure a new update site http://dist.codehaus.org/groovy/distributions/update/ 3. Follow the wizard instructions 4. Restart Eclipse. You are now ready to start Groovying! Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 51
  • 52. Resources • Groovy Language, guides, examples  http://groovy.codehaus.org • Groovy Eclipse Plugin  http://groovy.codehaus.org/Eclipse+Plugin • Groovy Related News  http://aboutgroovy.com  http://groovyblogs.org  http://groovy.dzone.com • My Groovy/Java/Swing blog  http://jroller.com/aalmiray  http://twitter.com/aalmiray Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 52
  • 53. Q&A © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  • 54. Thank you! © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009