SlideShare a Scribd company logo
Learning Groovy (in 3 hours)!
Adam L. Davis
The Solution Design Group, Inc.
Author of “Learning Groovy”
(& What’s New in Java 8 & others)
14 years Java Dev.
github.com/adamldavis
/2017-gr8conf-learning-groovy
Java ~ Brian Goetz (Java Language Architect)
Groovy
<Insert your
hated language
here>
PHP
groovy-lang.org
sdkman.io
● Dynamic or Static
● (@CompileStatic @TypeChecked)
● As fast as Java (with static & indy)
● Meta-programming
● Optional semi-colons
● Optional parentheses
● Short-hand for Lists and Maps
● Automatic getters and setters
● A better switch
● Groovy GDK…
Groovy 2.4 Features
● Closures
● Currying
● Method references
● Map/Filter/Reduce as collect, findAll, inject
● Internal iterating using each
● Operator Overloading (+ - * % / …)
● methodMissing and propertyMissing
● AST Transformations
● Traits
…
Groovy 2.4 Features (cont.)
Starting Out
Option 1: Using sdkman.io
– sdk install groovy 2.4.9
Option 2: Download from groovy-lang.org
– Alter your PATH
● Export PATH=$PATH:/usr/lib/groovy/bin
● Option 3: Mac – see http://groovy-lang.org/install.html
● Option π: Windows – see https://github.com/groovy/groovy-windows-installer
Then: $ groovyConsole
IntelliJ IDEA or NetBeans
Dynamic typing
● def keyword
● Parameters’ typing optional
● Possible to mock using a map
– def dog = [bark: { println ‘woof’ }]
● Using @TypeChecked or @CompileStatic you
can make Groovy statically typed in some
classes
Groovy Strings
● ‘normal string’
● “groovy string can contain $variables”
● “can also do expressions ${x + 1}”
● Use triple quote to start/end multi-line strings
‘’’
This is a
Multi-line
String
‘’’
Math, Groovy Truth, and Equals
● Numbers are BigDecimal by default not Double
– 3.14 is a BigDecimal
– 3.14d is a Double
● Groovy truth: null, “”, [], 0 are false
– if (!thing) println “thing was null”
– if (!str) println “str was empty”
● Groovy == means .equals
– For identity use a.is(b)
Property Access
● Everything is public
by default
● Every field has a
getter and setter by
default
● Gotcha’s
– Map access
– String.class->String
● Property access automatically
uses getters and setters
● foo.bar == foo.getBar()
● foo.bar = 2 == foo.setBar(2)
Lists and Maps
● def emptyList = [ ]
● def emptyMap = [:]
● def numList = [1,2,3]
● def strMap = [cars: 1, boats: 2, planes: 3]
● def varMap = [(var1): 1, (var2): 2, (var3): 3]
Maps Continued...
● def map = [cars: 1, boats: 2, planes: 3]
● String key access: map.cars
● OR map[‘cars’]
● Also works for modifying:
– map.cars = 42
– map[‘cars’] = 42
Code Demo
A better switch
● Switch can use types, lists, ranges, patterns…
Switch (x) {
case Map: println “was a map”; break
case [4,5,6]: println “was 4, 5 or 6”; break
case 0..20: println “was 0 to 20”; break
case ~/w+/: println “ was a word”; break
case “hello”: println x; break
case BigDecimal: println “was a BigDecimal”
Groovy GDK
● Adds methods to everything! Adds its own classes...
● Collections: sort, findAll, collect, inject, each,…
● IO: toFile(), text, bytes, withReader, URL.content
● Ranges: x..y, x..<y
– GetAt syntax for Strings and Lists:
● text[0..4] == text.substring(0,5)
● Utilities: ConfigSlurper, Expando, ObservableList/Map/Set
Safe dereference & Elvis operator
● Safe dereference ?.
– String name = person?.name
– Java: person == null ? null : person.getName()
● Elvis operator ?:
– String name = person?.name ?: “Bob”
– Java: if (name == null) name = “Bob”
Closures
● Closure: “a self-containing method” (like Lambda exp.)
– def say = { x -> println x }
– say(‘hello gr8conf’)
– def say = { println it }
– def adder = { x, y -> x + y }
● Closures have several implicit variables:
– it - If the closure has one argument
– this - Refers to the enclosing class
– owner - The same as this unless it is enclosed in another closure.
– delegate - Usually the same as owner but you can change it (this
allows the methods of delegate to be in scope).
Closures Continued...
● When used as last parameter, closure can go
outside parentheses
– methodCalled(param1, param2) { closureHere() }
– methodWithOnlyClosure { closureHere() }
Regex Pattern Matching
● Regex = regular expressions
● Within forward slashes / is a regex
– You don’t need to use double 
● =~ for matching anywhere within a string
– if (text =~ /d+/) println “there was a number in it”
● ==~ for matching the whole string
– if (email ==~ /[w.]+@[w.]+/) println “it’s an email”
Meta-programming
● Every class and instance has a metaClass
● String.metaClass.upper =
{ delegate.toUpperCase() }
– “foo”.upper() == “FOO”
● Traits can be used as
mixins
● Maps can be cast to
actual types using as
[bark: {println “Woof!”}]
as Dog
Code Demo
Other Surprises for Java Devs
● Default values for method parameters
● groovy.transform.*
– @EqualsAndHashCode
– @TupleConstructor
– @ToString
– @Canonical
● Generics not enforced by default
Advanced Groovy
● Groovy Design Patterns
– Strategy pattern
– Categories
– Method caching
● DSLs – Domain Specific Languages
– Operator Overloading
● Traits
● Functional Programming
– curry
Spock
Grails
Gradle grooscript
The Groovy Ecosystem
and many others….
Griffon
Gradle
Imperative, not declarative
Relies on plugins
Tasks
Vanilla groovy
Easy to build plugins
Easy to do sub-projects
Spock
Built on JUnit
Somewhat enhanced groovy
“test names can be any string”
given: when: then: expect:
Built-in mocking
Table-syntax for provided test data
Pretty assert output
Thanks!
Adam L. Davis
“Learning Groovy”
github.com/adamldavis
/2017-gr8conf-learning-groovy
adamldavis.com
@adamldavis
groocss.org
@groocss
How? Gedit + https://github.com/aeischeid/gedit-grails-bundle

More Related Content

PDF
Learning groovy -EU workshop
PDF
Writing Groovy DSLs
PPTX
Java8 and Functional Programming
PPTX
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
PDF
EROSについて
ODP
Groovy Ast Transformations (greach)
PDF
FTD JVM Internals
PPTX
Typescript - A developer friendly javascript
Learning groovy -EU workshop
Writing Groovy DSLs
Java8 and Functional Programming
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
EROSについて
Groovy Ast Transformations (greach)
FTD JVM Internals
Typescript - A developer friendly javascript

What's hot (20)

PPTX
Groovy Programming Language
PPT
Groovy presentation
PDF
Introduction to Go programming language
PDF
Python Workshop. LUG Maniapl
PPT
Project Lambda - Closures after all?
PDF
Pune Clojure Course Outline
PDF
Defect prevention software
PDF
An Introduction to Game Programming with Flash: Object Oriented Programming
PPTX
Briefly Rust
PDF
Fantom - Programming Language for JVM, CLR, and Javascript
PPTX
Making Java Groovy (JavaOne 2013)
PPT
Algorithmic Notations
PDF
Algorithm and Programming (Procedure and Function)
PPT
Gentle introduction to modern C++
PDF
What make Swift Awesome
PPTX
Compile time polymorphism
PDF
JVM Performance Magic Tricks
PDF
Lec12-CS110 Computational Engineering
PDF
Using R in remote computer clusters
PPTX
C++11: Feel the New Language
Groovy Programming Language
Groovy presentation
Introduction to Go programming language
Python Workshop. LUG Maniapl
Project Lambda - Closures after all?
Pune Clojure Course Outline
Defect prevention software
An Introduction to Game Programming with Flash: Object Oriented Programming
Briefly Rust
Fantom - Programming Language for JVM, CLR, and Javascript
Making Java Groovy (JavaOne 2013)
Algorithmic Notations
Algorithm and Programming (Procedure and Function)
Gentle introduction to modern C++
What make Swift Awesome
Compile time polymorphism
JVM Performance Magic Tricks
Lec12-CS110 Computational Engineering
Using R in remote computer clusters
C++11: Feel the New Language
Ad

Similar to Learning groovy 1: half day workshop (20)

PDF
Groovy.pptx
PDF
Introduction to Groovy (Serbian Developer Conference 2013)
PPT
Groovy Update - JavaPolis 2007
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
PDF
An Introduction to Groovy for Java Developers
PDF
Apache Groovy: the language and the ecosystem
PDF
Introductionto fp with groovy
PPT
Groovy Basics
ODP
PPT
Groovy unleashed
PDF
Infinum android talks_10_getting groovy on android
ODP
Getting Groovy
PDF
Practical Groovy DSL
PPTX
Groovy And Grails Introduction
PPTX
Groovy Api Tutorial
PDF
Introduction to Oracle Groovy
PPTX
getting-your-groovy-on
PDF
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
PDF
Oscon Java Testing on the Fast Lane
PPTX
Groovy features
Groovy.pptx
Introduction to Groovy (Serbian Developer Conference 2013)
Groovy Update - JavaPolis 2007
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
An Introduction to Groovy for Java Developers
Apache Groovy: the language and the ecosystem
Introductionto fp with groovy
Groovy Basics
Groovy unleashed
Infinum android talks_10_getting groovy on android
Getting Groovy
Practical Groovy DSL
Groovy And Grails Introduction
Groovy Api Tutorial
Introduction to Oracle Groovy
getting-your-groovy-on
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
Oscon Java Testing on the Fast Lane
Groovy features
Ad

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Empathic Computing: Creating Shared Understanding
DOCX
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
Spectral efficient network and resource selection model in 5G networks
sap open course for s4hana steps from ECC to s4
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
20250228 LYD VKU AI Blended-Learning.pptx
A comparative analysis of optical character recognition models for extracting...
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Empathic Computing: Creating Shared Understanding
The AUB Centre for AI in Media Proposal.docx

Learning groovy 1: half day workshop

  • 1. Learning Groovy (in 3 hours)! Adam L. Davis The Solution Design Group, Inc. Author of “Learning Groovy” (& What’s New in Java 8 & others) 14 years Java Dev. github.com/adamldavis /2017-gr8conf-learning-groovy
  • 2. Java ~ Brian Goetz (Java Language Architect)
  • 6. ● Dynamic or Static ● (@CompileStatic @TypeChecked) ● As fast as Java (with static & indy) ● Meta-programming ● Optional semi-colons ● Optional parentheses ● Short-hand for Lists and Maps ● Automatic getters and setters ● A better switch ● Groovy GDK… Groovy 2.4 Features
  • 7. ● Closures ● Currying ● Method references ● Map/Filter/Reduce as collect, findAll, inject ● Internal iterating using each ● Operator Overloading (+ - * % / …) ● methodMissing and propertyMissing ● AST Transformations ● Traits … Groovy 2.4 Features (cont.)
  • 8. Starting Out Option 1: Using sdkman.io – sdk install groovy 2.4.9 Option 2: Download from groovy-lang.org – Alter your PATH ● Export PATH=$PATH:/usr/lib/groovy/bin ● Option 3: Mac – see http://groovy-lang.org/install.html ● Option π: Windows – see https://github.com/groovy/groovy-windows-installer Then: $ groovyConsole IntelliJ IDEA or NetBeans
  • 9. Dynamic typing ● def keyword ● Parameters’ typing optional ● Possible to mock using a map – def dog = [bark: { println ‘woof’ }] ● Using @TypeChecked or @CompileStatic you can make Groovy statically typed in some classes
  • 10. Groovy Strings ● ‘normal string’ ● “groovy string can contain $variables” ● “can also do expressions ${x + 1}” ● Use triple quote to start/end multi-line strings ‘’’ This is a Multi-line String ‘’’
  • 11. Math, Groovy Truth, and Equals ● Numbers are BigDecimal by default not Double – 3.14 is a BigDecimal – 3.14d is a Double ● Groovy truth: null, “”, [], 0 are false – if (!thing) println “thing was null” – if (!str) println “str was empty” ● Groovy == means .equals – For identity use a.is(b)
  • 12. Property Access ● Everything is public by default ● Every field has a getter and setter by default ● Gotcha’s – Map access – String.class->String ● Property access automatically uses getters and setters ● foo.bar == foo.getBar() ● foo.bar = 2 == foo.setBar(2)
  • 13. Lists and Maps ● def emptyList = [ ] ● def emptyMap = [:] ● def numList = [1,2,3] ● def strMap = [cars: 1, boats: 2, planes: 3] ● def varMap = [(var1): 1, (var2): 2, (var3): 3]
  • 14. Maps Continued... ● def map = [cars: 1, boats: 2, planes: 3] ● String key access: map.cars ● OR map[‘cars’] ● Also works for modifying: – map.cars = 42 – map[‘cars’] = 42
  • 16. A better switch ● Switch can use types, lists, ranges, patterns… Switch (x) { case Map: println “was a map”; break case [4,5,6]: println “was 4, 5 or 6”; break case 0..20: println “was 0 to 20”; break case ~/w+/: println “ was a word”; break case “hello”: println x; break case BigDecimal: println “was a BigDecimal”
  • 17. Groovy GDK ● Adds methods to everything! Adds its own classes... ● Collections: sort, findAll, collect, inject, each,… ● IO: toFile(), text, bytes, withReader, URL.content ● Ranges: x..y, x..<y – GetAt syntax for Strings and Lists: ● text[0..4] == text.substring(0,5) ● Utilities: ConfigSlurper, Expando, ObservableList/Map/Set
  • 18. Safe dereference & Elvis operator ● Safe dereference ?. – String name = person?.name – Java: person == null ? null : person.getName() ● Elvis operator ?: – String name = person?.name ?: “Bob” – Java: if (name == null) name = “Bob”
  • 19. Closures ● Closure: “a self-containing method” (like Lambda exp.) – def say = { x -> println x } – say(‘hello gr8conf’) – def say = { println it } – def adder = { x, y -> x + y } ● Closures have several implicit variables: – it - If the closure has one argument – this - Refers to the enclosing class – owner - The same as this unless it is enclosed in another closure. – delegate - Usually the same as owner but you can change it (this allows the methods of delegate to be in scope).
  • 20. Closures Continued... ● When used as last parameter, closure can go outside parentheses – methodCalled(param1, param2) { closureHere() } – methodWithOnlyClosure { closureHere() }
  • 21. Regex Pattern Matching ● Regex = regular expressions ● Within forward slashes / is a regex – You don’t need to use double ● =~ for matching anywhere within a string – if (text =~ /d+/) println “there was a number in it” ● ==~ for matching the whole string – if (email ==~ /[w.]+@[w.]+/) println “it’s an email”
  • 22. Meta-programming ● Every class and instance has a metaClass ● String.metaClass.upper = { delegate.toUpperCase() } – “foo”.upper() == “FOO” ● Traits can be used as mixins ● Maps can be cast to actual types using as [bark: {println “Woof!”}] as Dog
  • 24. Other Surprises for Java Devs ● Default values for method parameters ● groovy.transform.* – @EqualsAndHashCode – @TupleConstructor – @ToString – @Canonical ● Generics not enforced by default
  • 25. Advanced Groovy ● Groovy Design Patterns – Strategy pattern – Categories – Method caching ● DSLs – Domain Specific Languages – Operator Overloading ● Traits ● Functional Programming – curry
  • 26. Spock Grails Gradle grooscript The Groovy Ecosystem and many others…. Griffon
  • 27. Gradle Imperative, not declarative Relies on plugins Tasks Vanilla groovy Easy to build plugins Easy to do sub-projects
  • 28. Spock Built on JUnit Somewhat enhanced groovy “test names can be any string” given: when: then: expect: Built-in mocking Table-syntax for provided test data Pretty assert output
  • 29. Thanks! Adam L. Davis “Learning Groovy” github.com/adamldavis /2017-gr8conf-learning-groovy adamldavis.com @adamldavis groocss.org @groocss How? Gedit + https://github.com/aeischeid/gedit-grails-bundle