SlideShare a Scribd company logo
Introduction to Groovy
Agenda What is Groovy From Java to Groovy Feature
What is Groovy? Groovy is an agile and  dynamic  language for the Java Virtual Machine  Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby & Smalltalk  Makes modern programming features available to Java developers with  almost-zero learning curve Supports  Domain Specific Languages  and other compact syntax so your code becomes easy to read and maintain
What is Groovy? Increases developer productivity by  reducing scaffolding  code when developing web, GUI, database or console applications  Simplifies testing  by supporting unit testing and mocking out-of-the-box  Seamlessly integrates  with all existing Java objects and libraries  Compiles straight to Java byte code so you can  use it anywhere you can use Java
From Java to Groovy
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  “Hello “ + name; } public   static void  main(String args[]){ HelloWorld helloWorld =  new  HelloWorld() helloWorld.setName( “Groovy” ) System.err.println( helloWorld.greet() ) } }
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  “Hello “ + name; } public   static void  main(String args[]){ HelloWorld helloWorld =  new  HelloWorld() helloWorld.setName( “Groovy” ) System.err.println( helloWorld.greet() ) } }
Everything in Groovy is public unless defined otherwise. Semicolons at end-of-line are optional.
class  HelloWorld { String name void  setName(String name) { this.name = name } String getName(){ return name } String greet() { return  "Hello " + name } static void  main(String args[]){ HelloWorld helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) System.err.println( helloWorld.greet() ) } }
Programming a JavaBean requires a pair of get/set for each property, we all know that. Let Groovy write those for you! Main( ) always requires String[ ] as parameter. Make that method definition shorter with optional types! Printing to the console is so common, can we get a shorter version too?
class  HelloWorld { String name String greet() { return  "Hello " + name } static void  main( args ){ HelloWorld helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) println( helloWorld.greet() ) } }
Use the  def  keyword when you do not care about the type of a variable, think of it as the  var  keyword in JavaScript. Groovy will figure out the correct type, this is called  duck typing .
class  HelloWorld { String name def  greet() { return  "Hello " + name } static def  main( args ){ def  helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) println( helloWorld.greet() ) } }
Groovy supports variable interpolation through GStrings (seriously, that is the correct name!) It works as you would expect in other languages. Prepend any Groovy expression with ${} inside a String
class  HelloWorld { String name def  greet(){ return  "Hello ${name}"  } static def  main( args ){ def  helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) println( helloWorld.greet() ) } }
The return keyword is optional, the return value of a method will be the last evaluated expression. You do not need to use def in static methods
class  HelloWorld { String name def  greet(){  "Hello ${name}"  } static  main( args ){ def  helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) println( helloWorld.greet() ) } }
Not only do POJOs (we call them POGOs in Groovy) write their own property accessors, they also provide a default constructor with named parameters (kind of). POGOs support the array subscript (bean[prop]) and dot notation (bean.prop) to access properties
class  HelloWorld { String name def  greet(){  "Hello ${name}"  } static  main( args ){ def  helloWorld =  new HelloWorld(name: "Groovy" ) helloWorld.name =  "Groovy" helloWorld[ " name " ] =  "Groovy" println( helloWorld.greet() ) } }
Even though Groovy compiles classes to Java byte code, it also supports scripts, and guess what, they are also compile down to Java byte code. Scripts allow classes to be defined anywhere on them. Scripts support packages, after all they are also valid Java classes.
class  HelloWorld { String name def  greet() {  "Hello $name"   } } def  helloWorld =  new  HelloWorld(name : " Groovy" ) println helloWorld.greet()
Java public class  HelloWorld { String name; public   void  setName(String name) { this.name = name; } public  String getName(){ return name; } public  String greet() { return  "Hello " + name; } public   static void  main(String args[]){ HelloWorld helloWorld =  new  HelloWorld() helloWorld.setName( "Groovy" ) System.err.println( helloWorld.greet() ) } }
Groovy class  HelloWorld { String name def  greet() {  "Hello $name"   } } def  helloWorld =  new  HelloWorld(name : " Groovy" ) println helloWorld.greet()
Feature
Java is Groovy, Groovy is Java Flat learning curve for Java developers, start with straight Java syntax then move on to a groovier syntax as you feel comfortable. Almost 98% Java code is Groovy code, meaning you can in most changes rename *.java to *.groovy and it will work.
Some other features added to Groovy not available in Java Native syntax for maps and arrays def myMap = ["Austin":35, "Scott":20] Native support for regular expressions if ("name" ==~ "na.*" ) { println "wow" } Embedded expressions inside strings def name="jussi"; println "hello $name" New helper methods added to the JDK For example String contains methods count(), tokenize(), each() You can add your own methods to existing classes Operator overloading a + b maps to a.plus(b)
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.
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
Iterators everywhere As 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
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  "list[$i] => $v"  } // list[0] => 1 // list[1] => 2 // list[2] => 3 // list[3] => 4 // list[4] => 5
The  as  keyword Used for “Groovy casting”, convert a value of typeA into a value of typeB def  intarray = [1,2,3]  as  int[ ]
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)
XML Generation import  groovy.xml.* data  = [ 'Rod' : [ 'Misha' :9,  'Bowie' :3], 'Eric' : [ 'Poe' :5,  'Doc' :4] ] def   xml   = new MarkupBuilder() doc  =  xml.people() { for (   s   in   data)   { person(name:   s . key )  { for ( d   in   s . value )  { pet(name:d . key ,  age : d . value ) } } } } println   doc
Output <people> <person name='Rod'> <pet name='Bowie' age='3' /> <pet name='Misha' age='9' /> </person> <person name='Eric'> <pet name='Poe' age='5' /> <pet name='Doc' age='4' /> </person> </people>

More Related Content

PDF
awesome groovy
PDF
functional groovy
PDF
groovy rules
PDF
tictactoe groovy
PDF
Atlassian Groovy Plugins
PDF
(Greach 2015) Dsl'ing your Groovy
PDF
Polyglot JVM
PDF
Designing with Groovy Traits - Gr8Conf India
awesome groovy
functional groovy
groovy rules
tictactoe groovy
Atlassian Groovy Plugins
(Greach 2015) Dsl'ing your Groovy
Polyglot JVM
Designing with Groovy Traits - Gr8Conf India

What's hot (20)

PDF
Oleksii Holub "Expression trees in C#"
PDF
Expression trees in C#
PPT
Polyglot Programming in the JVM
PPTX
concurrency gpars
KEY
Polyglot Grails
PDF
Logic programming a ruby perspective
ODP
GPars (Groovy Parallel Systems)
PPTX
python beginner talk slide
KEY
Erlang/OTP for Rubyists
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
PDF
Grooscript gr8conf
PPTX
Making Java Groovy (JavaOne 2013)
PDF
Functional programming in java
PPTX
Top 20 java programming interview questions for sdet
PPT
Eclipsecon08 Introduction To Groovy
PDF
core.logic introduction
PPT
Functional Programming In Java
ZIP
Round PEG, Round Hole - Parsing Functionally
PPTX
C# Is The Future
PDF
Python Workshop. LUG Maniapl
Oleksii Holub "Expression trees in C#"
Expression trees in C#
Polyglot Programming in the JVM
concurrency gpars
Polyglot Grails
Logic programming a ruby perspective
GPars (Groovy Parallel Systems)
python beginner talk slide
Erlang/OTP for Rubyists
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
Grooscript gr8conf
Making Java Groovy (JavaOne 2013)
Functional programming in java
Top 20 java programming interview questions for sdet
Eclipsecon08 Introduction To Groovy
core.logic introduction
Functional Programming In Java
Round PEG, Round Hole - Parsing Functionally
C# Is The Future
Python Workshop. LUG Maniapl
Ad

Similar to Introduction To Groovy (20)

PPT
Groovy for Java Developers
PPT
2007 09 10 Fzi Training Groovy Grails V Ws
PPTX
Groovy Api Tutorial
PPT
Groovy Update - JavaPolis 2007
PPT
Groovy Introduction - JAX Germany - 2008
PPT
What's New in Groovy 1.6?
PDF
Whats New In Groovy 1.6?
PDF
Introduction to Oracle Groovy
PDF
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
ZIP
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
PPTX
Groovy Programming Language
PPT
Introduction To Groovy 2005
PPT
Groovy & Grails: Scripting for Modern Web Applications
PDF
Groovy On Trading Desk (2010)
PPT
Groovy presentation
PDF
Practical Domain-Specific Languages in Groovy
KEY
Groovy & Grails
PDF
Eclipsecon09 Introduction To Groovy
PPT
Groovy Basics
PPT
Svcc Groovy Testing
Groovy for Java Developers
2007 09 10 Fzi Training Groovy Grails V Ws
Groovy Api Tutorial
Groovy Update - JavaPolis 2007
Groovy Introduction - JAX Germany - 2008
What's New in Groovy 1.6?
Whats New In Groovy 1.6?
Introduction to Oracle Groovy
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy Programming Language
Introduction To Groovy 2005
Groovy & Grails: Scripting for Modern Web Applications
Groovy On Trading Desk (2010)
Groovy presentation
Practical Domain-Specific Languages in Groovy
Groovy & Grails
Eclipsecon09 Introduction To Groovy
Groovy Basics
Svcc Groovy Testing
Ad

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PPT
Teaching material agriculture food technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Approach and Philosophy of On baking technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Machine learning based COVID-19 study performance prediction
PDF
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
Teaching material agriculture food technology
Advanced methodologies resolving dimensionality complications for autism neur...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Approach and Philosophy of On baking technology
Understanding_Digital_Forensics_Presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Mobile App Security Testing_ A Comprehensive Guide.pdf
Review of recent advances in non-invasive hemoglobin estimation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Machine learning based COVID-19 study performance prediction
Chapter 3 Spatial Domain Image Processing.pdf

Introduction To Groovy

  • 2. Agenda What is Groovy From Java to Groovy Feature
  • 3. What is Groovy? Groovy is an agile and dynamic language for the Java Virtual Machine Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby & Smalltalk Makes modern programming features available to Java developers with almost-zero learning curve Supports Domain Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • 4. What is Groovy? Increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications Simplifies testing by supporting unit testing and mocking out-of-the-box Seamlessly integrates with all existing Java objects and libraries Compiles straight to Java byte code so you can use it anywhere you can use Java
  • 5. From Java to Groovy
  • 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 “Hello “ + name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName( “Groovy” ) System.err.println( helloWorld.greet() ) } }
  • 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 “Hello “ + name; } public static void main(String args[]){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName( “Groovy” ) System.err.println( helloWorld.greet() ) } }
  • 8. Everything in Groovy is public unless defined otherwise. Semicolons at end-of-line are optional.
  • 9. 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;Groovy&quot; ) System.err.println( helloWorld.greet() ) } }
  • 10. Programming a JavaBean requires a pair of get/set for each property, we all know that. Let Groovy write those for you! Main( ) always requires String[ ] as parameter. Make that method definition shorter with optional types! Printing to the console is so common, can we get a shorter version too?
  • 11. class HelloWorld { String name String greet() { return &quot;Hello &quot; + name } static void main( args ){ HelloWorld helloWorld = new HelloWorld() helloWorld.setName( &quot;Groovy&quot; ) println( helloWorld.greet() ) } }
  • 12. Use the def keyword when you do not care about the type of a variable, think of it as the var keyword in JavaScript. Groovy will figure out the correct type, this is called duck typing .
  • 13. class HelloWorld { String name def greet() { return &quot;Hello &quot; + name } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName( &quot;Groovy&quot; ) println( helloWorld.greet() ) } }
  • 14. Groovy supports variable interpolation through GStrings (seriously, that is the correct name!) It works as you would expect in other languages. Prepend any Groovy expression with ${} inside a String
  • 15. class HelloWorld { String name def greet(){ return &quot;Hello ${name}&quot; } static def main( args ){ def helloWorld = new HelloWorld() helloWorld.setName( &quot;Groovy&quot; ) println( helloWorld.greet() ) } }
  • 16. The return keyword is optional, the return value of a method will be the last evaluated expression. You do not need to use def in static methods
  • 17. class HelloWorld { String name def greet(){ &quot;Hello ${name}&quot; } static main( args ){ def helloWorld = new HelloWorld() helloWorld.setName( &quot;Groovy&quot; ) println( helloWorld.greet() ) } }
  • 18. Not only do POJOs (we call them POGOs in Groovy) write their own property accessors, they also provide a default constructor with named parameters (kind of). POGOs support the array subscript (bean[prop]) and dot notation (bean.prop) to access properties
  • 19. class HelloWorld { String name def greet(){ &quot;Hello ${name}&quot; } static main( args ){ def helloWorld = new HelloWorld(name: &quot;Groovy&quot; ) helloWorld.name = &quot;Groovy&quot; helloWorld[ &quot; name &quot; ] = &quot;Groovy&quot; println( helloWorld.greet() ) } }
  • 20. Even though Groovy compiles classes to Java byte code, it also supports scripts, and guess what, they are also compile down to Java byte code. Scripts allow classes to be defined anywhere on them. Scripts support packages, after all they are also valid Java classes.
  • 21. class HelloWorld { String name def greet() { &quot;Hello $name&quot; } } def helloWorld = new HelloWorld(name : &quot; Groovy&quot; ) println helloWorld.greet()
  • 22. 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;Groovy&quot; ) System.err.println( helloWorld.greet() ) } }
  • 23. Groovy class HelloWorld { String name def greet() { &quot;Hello $name&quot; } } def helloWorld = new HelloWorld(name : &quot; Groovy&quot; ) println helloWorld.greet()
  • 25. Java is Groovy, Groovy is Java Flat learning curve for Java developers, start with straight Java syntax then move on to a groovier syntax as you feel comfortable. Almost 98% Java code is Groovy code, meaning you can in most changes rename *.java to *.groovy and it will work.
  • 26. Some other features added to Groovy not available in Java Native syntax for maps and arrays def myMap = [&quot;Austin&quot;:35, &quot;Scott&quot;:20] Native support for regular expressions if (&quot;name&quot; ==~ &quot;na.*&quot; ) { println &quot;wow&quot; } Embedded expressions inside strings def name=&quot;jussi&quot;; println &quot;hello $name&quot; New helper methods added to the JDK For example String contains methods count(), tokenize(), each() You can add your own methods to existing classes Operator overloading a + b maps to a.plus(b)
  • 27. 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.
  • 28. 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
  • 29. Iterators everywhere As 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
  • 30. 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] => $v&quot; } // list[0] => 1 // list[1] => 2 // list[2] => 3 // list[3] => 4 // list[4] => 5
  • 31. The as keyword Used for “Groovy casting”, convert a value of typeA into a value of typeB def intarray = [1,2,3] as int[ ]
  • 32. 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)
  • 33. XML Generation import groovy.xml.* data = [ 'Rod' : [ 'Misha' :9, 'Bowie' :3], 'Eric' : [ 'Poe' :5, 'Doc' :4] ] def xml = new MarkupBuilder() doc = xml.people() { for ( s in data) { person(name: s . key ) { for ( d in s . value ) { pet(name:d . key , age : d . value ) } } } } println doc
  • 34. Output <people> <person name='Rod'> <pet name='Bowie' age='3' /> <pet name='Misha' age='9' /> </person> <person name='Eric'> <pet name='Poe' age='5' /> <pet name='Doc' age='4' /> </person> </people>