0
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 featur...
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...
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)
        { t...
HelloWorld in Groovy
    public class HelloWorld {
       String name;

        public void setName(String name)
        {...
Step 1: Let’s get rid of the noise
    public class HelloWorld {
       String name;

        public void setName(String n...
Step 1 - Results
    class HelloWorld {
       String name

        void setName(String name)
        { this.name = name }...
Step 2: let’s get rid of boilerplate
     class HelloWorld {
        String name

         void setName(String name)
     ...
Step 2 - Results
     class HelloWorld {
        String name

         String greet()
         { return quot;Hello quot;+ ...
Step 3: Introduce dynamic types
     class HelloWorld {
        String name

         String greet()
         { return quo...
Step 3 - Results
     class HelloWorld {
        String name

         def greet()
         { return quot;Hello quot;+ nam...
Step 4: Use variable interpolation
     class HelloWorld {
        String name

         def greet(){ return quot;Hello qu...
Step 4 - Results
     class HelloWorld {
        String name

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

    ...
Step 5: Let’s get rid of more keywords
     class HelloWorld {
        String name

         def greet(){ return quot;Hell...
Step 5 - Results
     class HelloWorld {
        String name

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

         st...
Step 6: POJOs on steroids
     class HelloWorld {
        String name

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

  ...
Step 6 - Results
     class HelloWorld {
        String name

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

         st...
Step 7: Groovy supports scripts
     class HelloWorld {
        String name

         def greet(){ quot;Hello ${name}quot;...
Step 7 - Results
     class HelloWorld {
        String name
        def greet() { quot;Hello $namequot; }
     }

     de...
We came from here…
     public class HelloWorld {
        String name;

         public void setName(String name)
        ...
… to here
     class HelloWorld {
        String name
        def greet() { quot;Hello $namequot; }
     }

     def hello...
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:...
Varargs in action
     class Calculator {
        def addAllGroovy( Object[] args ){
           int total = 0
           f...
Scott Davis' 1st mantra:
                      Java is Groovy, Groovy is Java




          Introduction to Groovy | © 200...
Not-Java Features
        Explore the Neighborhood




© 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/...
Assorted goodies
     • Default parameter values as in PHP
     • Named parameters as in Ruby (reuse the Map trick of
    ...
Closures
     • Closures can be seen as reusable blocks of code, you
       may have seen them in JavaScript and Ruby amon...
Examples of closures
     def greet = { name -> println “Hello $name” }
     greet( “Groovy” )
     // prints Hello Groovy...
With closures comes currying
     • Currying is a programming technique that transforms a
       function into another whi...
Currying in action
     // a closure with 3 parameters, the third one is optional
     // as it defines a default value
  ...
Iterators everywhere
     • Like in Ruby you may use iterators in almost any
       context, Groovy will figure out what t...
Iterators in action
     def printIt = { println it }
     // 3 ways to iterate from 1 to 5
     [1,2,3,4,5].each printIt
...
Scott Davis' 2nd mantra:
          Groovy is Java and Groovy is NOT Java




         Introduction to Groovy | © 2009 by «...
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...
Some examples of as
     import javax.swing.table.DefaultTableCellRenderer as DTCR

     def myActionListener = { event ->...
New operators
     • ?: (elvis) - a refinement over the ternary operator

     • ?. Safe dereference – navigate an object ...
Traversing object graphs
     • GPath is to objects what XPath is to XML.

     • *. and ?. come in handy in many situatio...
Sample GPath expressions
     class Person {
        String name
        int id
     }

     def persons = [
        new P...
MetaProgramming

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

     • You can intercept call...
A simple example using categories
     class Pouncer {
        static pounce( Integer self ){
           def s = “Boing!qu...
Same example using MetaClasses
     Integer.metaClass.pounce << { ->
        def s = “Boing!quot;
        delegate.upto(de...
More options in Groovy 1.6!

     • Compile time metaprogramming via AST
       transformations

     • Runtime mixins



...
Scott Davis says:
      Groovy is what the Java language would look like
           had it been written in the 21st centur...
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
     •...
How to install
     1. Go to Help -> Software Updates -> Find and Install
     2. Configure a new update site
       http:...
Resources
     • Groovy Language, guides, examples
        http://groovy.codehaus.org
     • Groovy Eclipse Plugin
      ...
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
Upcoming SlideShare
Loading in...5
×

Eclipsecon09 Introduction To Groovy

1,907

Published on

Eclipsecon09 Introduction to Groovy

0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,907
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
80
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Transcript of "Eclipsecon09 Introduction To Groovy"

  1. 1. Introduction to Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  2. 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. 3. What is Groovy? © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  4. 4. http://www.flickr.com/photos/teagrrl/78941282/ Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 4
  5. 5. From Java to Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  6. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 24. Introduction to Groovy | © 2009 by «Andres Almiray»; made available under the EPL v1.0 24
  25. 25. Java-like Features Close to home © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  26. 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. 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. 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. 29. Not-Java Features Explore the Neighborhood © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  30. 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. 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. 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. 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. 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. 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. 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. 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. 38. Unique Features Space out! © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  39. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 49. Eclipse & Groovy © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  50. 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. 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. 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. 53. Q&A © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  54. 54. Thank you! © 2009 by «Andres Almiray»; made available under the EPL v1.0 | 03/25/2009
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×