SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Beginning Groovy 3.0
Adam L. Davis
The Solution Design Group, Inc.
Author of “Learning Groovy”
(& Reactive Streams in Java & others)
16 years Java Dev.
github.com/adamldavis
/2019-gr8conf
thesdg.com
Java ~ Brian Goetz (Java Language Architect)
Groovy
<Insert your
hated language
here>
PHP
groovy-lang.org
sdkman.io
Flat learning curve
Smooth Java integration
Vibrant and rich ecosystem
Powerful features
Domain-Specific Languages (DSLs)
Scripting and testing glue
Inspired by Python, Ruby,
Smalltalk, ...
●
Dynamic or Static
●
(@CompileStatic @TypeChecked)
●
As fast as Java (with static & indy)
●
Meta-programming
●
Optional semi-colons
●
Optional parentheses (command chains)
●
Short-hand for Lists and Maps
●
Automatic getters and setters
●
A better switch
●
Groovy GDK…
Groovy pre-2.5 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 pre-2.5 Features (cont.)
Groovy 2.5
●
Groovy 2.5 added support for JDK9+
●
11 new AST transformations
– @AutoFinal, @AutoImplement, @ImmutableBase,
@ImmutableOptions, @MapConstructor,
@NamedDelegate, @NamedParam,
@NamedParams, @NamedVariant,
@PropertyOptions, and @VisibilityOptions
●
Macro feature - makes writing AST
transformations much easier!
Starting Out
Option 1: Using sdkman.io
– sdk install groovy
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 or methodsz
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)
– Groovy 3: a === 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
Groovy 3
●
Groovy 3 sports a completely rewritten parser
(Parrot) that brings Groovy up to parity with the
latest Java 11 syntax along with new Groovy-only
features. It runs on JDK 8 minimum and has better
support for JDK 9/10/11.
●
Java-style: lambda expressions and method
references, array initialization, and do/while loops
●
Support for try-with-resources and “var”
●
New operators: !in !instanceof
Code Demo 1
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, JsonSlurper, JsonBuilder, ...
in keyword
●
Use the “in” keyword to test inclusion or loops:
– assert 'Groovy' in ['Java', 'Groovy']
– assert 7 in 0..10
– for (i in 0..10) {}
– for (str in strArray) {}
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 
– Example: /d+/ matches any number
●
=~ 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”
● ●
Extension Modules!
●
Traits can be used as
mixins
●
Maps can be cast to
actual types using as
[bark: {println “Woof!”}]
as Dog
Code Demo 2
Other Surprises for Java Devs
●
Default values for method parameters
●
Dot notation to call methods… object.”method name”
●
groovy.transform.*
– @EqualsAndHashCode
– @TupleConstructor
– @ToString
– @Canonical
●
Generics not enforced by default
– (use @CompileStatic to do it)
Advanced Groovy
●
Groovy Design Patterns
– Strategy pattern
– Categories
– Method caching
●
DSLs – Domain Specific Languages
– Operator Overloading
– Meta-programming, Extension Modules,
Closures, ...
●
Traits: multi-inheritance
More Groovy
●
Groovy Grapes
– @Grab(group=’’, module=’’, version=’’)
●
Functional Programming
– curry
– Closures, etc.
Code Demo 3
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
/2019-gr8conf
adamldavis.com
@adamldavis
http://bit.ly/Gr8-2019BG
How? Gedit + https://github.com/aeischeid/gedit-grails-bundle

Mais conteúdo relacionado

Mais procurados

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011
Patrick Walton
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 

Mais procurados (20)

Typescript - A developer friendly javascript
Typescript - A developer friendly javascriptTypescript - A developer friendly javascript
Typescript - A developer friendly javascript
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Crystal presentation in NY
Crystal presentation in NYCrystal presentation in NY
Crystal presentation in NY
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvand
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
Stripe CTF3 wrap-up
Stripe CTF3 wrap-upStripe CTF3 wrap-up
Stripe CTF3 wrap-up
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
 
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
DConf 2016: Bitpacking Like a Madman by Amaury SechetDConf 2016: Bitpacking Like a Madman by Amaury Sechet
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...
 
Introduction to Web Development - JavaScript
Introduction to Web Development - JavaScriptIntroduction to Web Development - JavaScript
Introduction to Web Development - JavaScript
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
What the C?
What the C?What the C?
What the C?
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
Android 101 - Building a simple app with Kotlin in 90 minutes
Android 101 - Building a simple app with Kotlin in 90 minutesAndroid 101 - Building a simple app with Kotlin in 90 minutes
Android 101 - Building a simple app with Kotlin in 90 minutes
 

Semelhante a Learning groovy -EU workshop

Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
Paul Lam
 

Semelhante a Learning groovy -EU workshop (20)

Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Writing Groovy DSLs
Writing Groovy DSLsWriting Groovy DSLs
Writing Groovy DSLs
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Experimental dtrace
Experimental dtraceExperimental dtrace
Experimental dtrace
 
Groovy
GroovyGroovy
Groovy
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Groovy to gradle
Groovy to gradleGroovy to gradle
Groovy to gradle
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
Golang
GolangGolang
Golang
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Learning groovy -EU workshop

  • 1. Beginning Groovy 3.0 Adam L. Davis The Solution Design Group, Inc. Author of “Learning Groovy” (& Reactive Streams in Java & others) 16 years Java Dev. github.com/adamldavis /2019-gr8conf thesdg.com
  • 2. Java ~ Brian Goetz (Java Language Architect)
  • 5. groovy-lang.org sdkman.io Flat learning curve Smooth Java integration Vibrant and rich ecosystem Powerful features Domain-Specific Languages (DSLs) Scripting and testing glue Inspired by Python, Ruby, Smalltalk, ...
  • 6. ● Dynamic or Static ● (@CompileStatic @TypeChecked) ● As fast as Java (with static & indy) ● Meta-programming ● Optional semi-colons ● Optional parentheses (command chains) ● Short-hand for Lists and Maps ● Automatic getters and setters ● A better switch ● Groovy GDK… Groovy pre-2.5 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 pre-2.5 Features (cont.)
  • 8. Groovy 2.5 ● Groovy 2.5 added support for JDK9+ ● 11 new AST transformations – @AutoFinal, @AutoImplement, @ImmutableBase, @ImmutableOptions, @MapConstructor, @NamedDelegate, @NamedParam, @NamedParams, @NamedVariant, @PropertyOptions, and @VisibilityOptions ● Macro feature - makes writing AST transformations much easier!
  • 9. Starting Out Option 1: Using sdkman.io – sdk install groovy 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
  • 10. 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 or methodsz
  • 11. 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 ‘’’
  • 12. 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) – Groovy 3: a === b
  • 13. 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)
  • 14. 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]
  • 15. 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. Groovy 3 ● Groovy 3 sports a completely rewritten parser (Parrot) that brings Groovy up to parity with the latest Java 11 syntax along with new Groovy-only features. It runs on JDK 8 minimum and has better support for JDK 9/10/11. ● Java-style: lambda expressions and method references, array initialization, and do/while loops ● Support for try-with-resources and “var” ● New operators: !in !instanceof
  • 18. 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”
  • 19. 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, JsonSlurper, JsonBuilder, ...
  • 20. in keyword ● Use the “in” keyword to test inclusion or loops: – assert 'Groovy' in ['Java', 'Groovy'] – assert 7 in 0..10 – for (i in 0..10) {} – for (str in strArray) {}
  • 21. 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”
  • 22. 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).
  • 23. Closures Continued... ● When used as last parameter, closure can go outside parentheses – methodCalled(param1, param2) { closureHere() } – methodWithOnlyClosure { closureHere() }
  • 24. Regex Pattern Matching ● Regex = regular expressions ● Within forward slashes / is a regex – You don’t need to use double – Example: /d+/ matches any number ● =~ 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”
  • 25. Meta-programming ● Every class and instance has a metaClass ● String.metaClass.upper = { delegate.toUpperCase() } – “foo”.upper() == “FOO” ● ● Extension Modules! ● Traits can be used as mixins ● Maps can be cast to actual types using as [bark: {println “Woof!”}] as Dog
  • 27. Other Surprises for Java Devs ● Default values for method parameters ● Dot notation to call methods… object.”method name” ● groovy.transform.* – @EqualsAndHashCode – @TupleConstructor – @ToString – @Canonical ● Generics not enforced by default – (use @CompileStatic to do it)
  • 28. Advanced Groovy ● Groovy Design Patterns – Strategy pattern – Categories – Method caching ● DSLs – Domain Specific Languages – Operator Overloading – Meta-programming, Extension Modules, Closures, ... ● Traits: multi-inheritance
  • 29. More Groovy ● Groovy Grapes – @Grab(group=’’, module=’’, version=’’) ● Functional Programming – curry – Closures, etc.
  • 31. Spock Grails Gradle grooscript The Groovy Ecosystem and many others…. Griffon
  • 32. Gradle Imperative, not declarative Relies on plugins Tasks Vanilla groovy Easy to build plugins Easy to do sub-projects
  • 33. 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
  • 34. Thanks! Adam L. Davis “Learning Groovy” github.com/adamldavis /2019-gr8conf adamldavis.com @adamldavis http://bit.ly/Gr8-2019BG How? Gedit + https://github.com/aeischeid/gedit-grails-bundle