SlideShare a Scribd company logo
1 of 29
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

What's hot

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG ManiaplAnkur Shrivastava
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?Andreas Enbohm
 
Defect prevention software
Defect prevention softwareDefect prevention software
Defect prevention softwareZarko Acimovic
 
An Introduction to Game Programming with Flash: Object Oriented Programming
An Introduction to Game Programming with Flash: Object Oriented ProgrammingAn Introduction to Game Programming with Flash: Object Oriented Programming
An Introduction to Game Programming with Flash: Object Oriented ProgrammingKrzysztof Opałka
 
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 JavascriptKamil Toman
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Ken Kousen
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Adam Mukharil Bachtiar
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift AwesomeSokna Ly
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic TricksTakipi
 
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringSri Harsha Pamu
 
Using R in remote computer clusters
Using R in remote computer clustersUsing R in remote computer clusters
Using R in remote computer clustersBurak Himmetoglu
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 

What's hot (20)

Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG Maniapl
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Defect prevention software
Defect prevention softwareDefect prevention software
Defect prevention software
 
An Introduction to Game Programming with Flash: Object Oriented Programming
An Introduction to Game Programming with Flash: Object Oriented ProgrammingAn Introduction to Game Programming with Flash: Object Oriented Programming
An Introduction to Game Programming with Flash: Object Oriented Programming
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
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
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 
Algorithmic Notations
Algorithmic NotationsAlgorithmic Notations
Algorithmic Notations
 
Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)Algorithm and Programming (Procedure and Function)
Algorithm and Programming (Procedure and Function)
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic Tricks
 
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational Engineering
 
Using R in remote computer clusters
Using R in remote computer clustersUsing R in remote computer clusters
Using R in remote computer clusters
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 

Similar to Learning groovy 1: half day 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 Railselliando dias
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Getting Groovy
Getting GroovyGetting Groovy
Getting GroovyAdam Davis
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with javaLiviu Tudor
 
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 GoRodolfo Carvalho
 
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
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovyIsuru Samaraweera
 
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 DevelopersKostas Saidis
 

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

Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
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 On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Experimental dtrace
Experimental dtraceExperimental dtrace
Experimental dtrace
 
Groovy to gradle
Groovy to gradleGroovy to gradle
Groovy to gradle
 
Getting Groovy
Getting GroovyGetting Groovy
Getting Groovy
 
Groovy
GroovyGroovy
Groovy
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Clojure
ClojureClojure
Clojure
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
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
 
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
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transforms
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
PigHive.pptx
PigHive.pptxPigHive.pptx
PigHive.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
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
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
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
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
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

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