SlideShare a Scribd company logo
1 of 70
Stop Writing JavaStart WritingGroovy EvgenyGoldin
Java => Groovy
equals vs. ==
Groovy runs Java .. except where it doesn’t. equals() / == == / is() Works with nulls assert null == null assertnull.is( null ) assertnull.equals( null )
Cleanups
Lose public Lose ; and return Lose .class Lose getX() / setX()
Lose public Lose ; and return Lose .class Lose getX() / setX() public String className( Class c ) { return c.getName(); } o.setName( className( Map.class ));
Lose public Lose ; and return Lose .class Lose getX() / setX() def className( Class c ) { c.name } o.name = className( Map )
Lose public Lose ; and return Lose .class Lose getX() / setX() http://codenarc.sourceforge.net/ http://plugins.intellij.net/plugin/?idea&id=5925
Lose public Lose ; and return Lose .class Lose getX() / setX() def className( Class c ) { c.name } o.name = className( Map ) It is a big deal at the end of the day
def j = 4
def j = 4 def list = [] def list = [1, 2, 3, 4]
def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4]
def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4] def array = [1, 2, 3, 4] as int[]
def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4] def array = [1, 2, 3, 4] as int[] new Thread({ print j } as Runnable).start()
Safe navigation
GroovyTruth
if (( o != null ) && ( o.size() > 0 )) { .. }
if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. }
if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. } Safe navigation operator : object?.method()
if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. } Safe navigation operator : object?.method() Groovy Truth: null is false Empty String, Map or Collection is false Zero number is false if ( list ), if ( string ), if ( map ), if ( o?.size()) ..
But
assert “false”
assert “false” assert “ “
assert “false” assert “ “ Object.asBoolean()
assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java      : Boolean.valueOf( String.valueOf( o ))
assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java      : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy
assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java      : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy Always specify if you use Java or Groovy Truth
assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java      : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy Always specify if you use Java or Groovy Truth
Elvis Operator
int j = ( o.size() > 0 ) ? o.size() : -1;
int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 )
int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?:defaultValue Takes defaultValue if value evaluates to false
int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?:defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings
int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?: defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings int j = ( size != null ) ? size : -1 int j = size ?: -1
int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?: defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings int j = ( size != null ) ? size : -1 // Accepts zero size int j = size ?: -1 // Doesn’t accept zero size
Default parameters
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); }
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } Overload
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. }
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. }
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. } def foo ( intj, int k = 1 ) { .. }
public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. } def foo ( intj, int k = 1 ) { .. } def foo ( int j  = f1(), intk = f2()) { .. }
GroovyBeans
public class Bean () {     private int j;     public intgetJ(){ return this.j; }     public void setJ( int j ){ this.j = j; } }
class Bean { int j } def b = new Bean() println ( b.j ) / println ( b.getJ()) b.j = 33 / b.setJ( 33 ) N Groovy beans can be kept in the same file
GStrings
def s = ‘aaaaaaa’
def s = ‘aaaaaaa’ def s = ’’’aaaaaaaaabbbbbbbb’’’
def s = ‘aaaaaaa’ def s = ’’’aaaaaaaaabbbbbbbb’’’ def s = “aaaaaaa” def s = ”””aaaaaaaaabbbbbbbb”””
def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb”””
def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb””” log.info ( String.format( “ .. %s .. ”, val )) log.info ( “ .. ${val} .. ” )
def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb””” assert "aaaaa".class == String assert "${1+2}".class == org.codehaus.groovy.runtime.GStringImpl
assert
if ( o == null ) {    throw new RuntimeException( “msg” ) }
if ( o == null ) {    throw new RuntimeException( “msg” ) } assert o, “msg”
if ( o == null ) {    throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg”
if ( o == null ) {    throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message”
if ( o == null ) {    throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message” assert false, “Fatal error”
if ( o == null ) {    throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message” assert false, “Fatal error” Asserting code samples is a common practice
def j = [1, 2]  def k = [3, 4]  assert j[0] == k[0]
def j = [1, 2]  def k = [3, 4]  assert j[0] == k[0]  Assertion failed:  assert j[0] == k[0]        ||   |  ||        |1   |  |3        |    |  [3, 4]        |    false        [1, 2]
GDK
http://groovy.codehaus.org/groovy-jdk/ Java+++
http://groovy.codehaus.org/groovy-jdk/ Java+++ Object String File Collection, Map, List, Set InputStream, OutputStream Reader, Writer
Object/Collection/Map each() any(), every() find(), findAll(), grep() join() collect() min(), max(), sum() inject()
String toURL() execute() eachLine() padLeft(), padRight() tr()
File deleteDir() eachLine() eachFileRecurse() getText() write(String) traverse()
Q&A

More Related Content

What's hot

How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
Giordano Scalzo
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
Anton Arhipov
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
it-people
 

What's hot (20)

How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right question
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
Pure kotlin
Pure kotlinPure kotlin
Pure kotlin
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Ruby on rails presentation
Ruby on rails presentationRuby on rails presentation
Ruby on rails presentation
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
Intro
IntroIntro
Intro
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
 

Viewers also liked

Our changing state: the realities of austerity and devolution
Our changing state: the realities of austerity and devolutionOur changing state: the realities of austerity and devolution
Our changing state: the realities of austerity and devolution
Browne Jacobson LLP
 
Icsi transformation 11-13 sept - agra
Icsi transformation   11-13 sept - agraIcsi transformation   11-13 sept - agra
Icsi transformation 11-13 sept - agra
Pavan Kumar Vijay
 
Créer et afficher une tag list sur scoop.it
Créer et afficher une tag list sur scoop.itCréer et afficher une tag list sur scoop.it
Créer et afficher une tag list sur scoop.it
Thierry Zenou
 

Viewers also liked (20)

Our changing state: the realities of austerity and devolution
Our changing state: the realities of austerity and devolutionOur changing state: the realities of austerity and devolution
Our changing state: the realities of austerity and devolution
 
LA Chef for OpenStack Hackday
LA Chef for OpenStack HackdayLA Chef for OpenStack Hackday
LA Chef for OpenStack Hackday
 
5 of the Biggest Myths about Growing Your Business
5 of the Biggest Myths about Growing Your Business5 of the Biggest Myths about Growing Your Business
5 of the Biggest Myths about Growing Your Business
 
BioBankCloud: Machine Learning on Genomics + GA4GH @ Med at Scale
BioBankCloud: Machine Learning on Genomics + GA4GH  @ Med at ScaleBioBankCloud: Machine Learning on Genomics + GA4GH  @ Med at Scale
BioBankCloud: Machine Learning on Genomics + GA4GH @ Med at Scale
 
Brief Encounter: London Zoo
Brief Encounter: London ZooBrief Encounter: London Zoo
Brief Encounter: London Zoo
 
Ngan hang-thuong-mai 2
Ngan hang-thuong-mai 2Ngan hang-thuong-mai 2
Ngan hang-thuong-mai 2
 
Italy weddings
Italy weddingsItaly weddings
Italy weddings
 
Simplifying life
Simplifying lifeSimplifying life
Simplifying life
 
Icsi transformation 11-13 sept - agra
Icsi transformation   11-13 sept - agraIcsi transformation   11-13 sept - agra
Icsi transformation 11-13 sept - agra
 
How to Improve Your Website
How to Improve Your WebsiteHow to Improve Your Website
How to Improve Your Website
 
Navigating Uncertainty when Launching New Ideas
Navigating Uncertainty when Launching New IdeasNavigating Uncertainty when Launching New Ideas
Navigating Uncertainty when Launching New Ideas
 
Alfred day hershy
Alfred day hershyAlfred day hershy
Alfred day hershy
 
Understanding the Big Picture of e-Science
Understanding the Big Picture of e-ScienceUnderstanding the Big Picture of e-Science
Understanding the Big Picture of e-Science
 
Parvat Pradesh Mein Pavas
Parvat Pradesh Mein PavasParvat Pradesh Mein Pavas
Parvat Pradesh Mein Pavas
 
Presentación taller 1
Presentación taller 1Presentación taller 1
Presentación taller 1
 
F.Blin IFLA Trend Report English_dk
F.Blin IFLA Trend Report English_dkF.Blin IFLA Trend Report English_dk
F.Blin IFLA Trend Report English_dk
 
Guía taller 2 a padres de familia ie medellin
Guía taller 2 a padres de familia ie medellinGuía taller 2 a padres de familia ie medellin
Guía taller 2 a padres de familia ie medellin
 
The Clientshare Academy Briefing - Gold Membership - by Practice Paradox
The Clientshare Academy Briefing - Gold Membership - by Practice ParadoxThe Clientshare Academy Briefing - Gold Membership - by Practice Paradox
The Clientshare Academy Briefing - Gold Membership - by Practice Paradox
 
De la aldea a los recintos ceremoniales en la sociedad andina del periodo ini...
De la aldea a los recintos ceremoniales en la sociedad andina del periodo ini...De la aldea a los recintos ceremoniales en la sociedad andina del periodo ini...
De la aldea a los recintos ceremoniales en la sociedad andina del periodo ini...
 
Créer et afficher une tag list sur scoop.it
Créer et afficher une tag list sur scoop.itCréer et afficher une tag list sur scoop.it
Créer et afficher une tag list sur scoop.it
 

Similar to Start Writing Groovy

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist
 

Similar to Start Writing Groovy (20)

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Kotlin
KotlinKotlin
Kotlin
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
Groovy
GroovyGroovy
Groovy
 
JavaScript @ CTK
JavaScript @ CTKJavaScript @ CTK
JavaScript @ CTK
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 

More from Evgeny Goldin

10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
Evgeny Goldin
 

More from Evgeny Goldin (9)

Alexa skills
Alexa skillsAlexa skills
Alexa skills
 
Polyglot Gradle with Node.js and Play
Polyglot Gradle with Node.js and PlayPolyglot Gradle with Node.js and Play
Polyglot Gradle with Node.js and Play
 
Node.js meets jenkins
Node.js meets jenkinsNode.js meets jenkins
Node.js meets jenkins
 
Functional Programming in Groovy
Functional Programming in GroovyFunctional Programming in Groovy
Functional Programming in Groovy
 
Release It!
Release It!Release It!
Release It!
 
Spock Extensions Anatomy
Spock Extensions AnatomySpock Extensions Anatomy
Spock Extensions Anatomy
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
 
Groovy Maven Builds
Groovy Maven BuildsGroovy Maven Builds
Groovy Maven Builds
 
Maven Plugins
Maven PluginsMaven Plugins
Maven Plugins
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Start Writing Groovy

  • 1. Stop Writing JavaStart WritingGroovy EvgenyGoldin
  • 3.
  • 5. Groovy runs Java .. except where it doesn’t. equals() / == == / is() Works with nulls assert null == null assertnull.is( null ) assertnull.equals( null )
  • 7. Lose public Lose ; and return Lose .class Lose getX() / setX()
  • 8. Lose public Lose ; and return Lose .class Lose getX() / setX() public String className( Class c ) { return c.getName(); } o.setName( className( Map.class ));
  • 9. Lose public Lose ; and return Lose .class Lose getX() / setX() def className( Class c ) { c.name } o.name = className( Map )
  • 10. Lose public Lose ; and return Lose .class Lose getX() / setX() http://codenarc.sourceforge.net/ http://plugins.intellij.net/plugin/?idea&id=5925
  • 11. Lose public Lose ; and return Lose .class Lose getX() / setX() def className( Class c ) { c.name } o.name = className( Map ) It is a big deal at the end of the day
  • 12. def j = 4
  • 13. def j = 4 def list = [] def list = [1, 2, 3, 4]
  • 14. def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4]
  • 15. def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4] def array = [1, 2, 3, 4] as int[]
  • 16. def j = 4 def list = [] def list = [1, 2, 3, 4] def map = [:] def map = [1:2, 3:4] def array = [1, 2, 3, 4] as int[] new Thread({ print j } as Runnable).start()
  • 19. if (( o != null ) && ( o.size() > 0 )) { .. }
  • 20. if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. }
  • 21. if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. } Safe navigation operator : object?.method()
  • 22. if (( o != null ) && ( o.size() > 0 )) { .. } if ( o?.size()) { .. } Safe navigation operator : object?.method() Groovy Truth: null is false Empty String, Map or Collection is false Zero number is false if ( list ), if ( string ), if ( map ), if ( o?.size()) ..
  • 23. But
  • 26. assert “false” assert “ “ Object.asBoolean()
  • 27. assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java : Boolean.valueOf( String.valueOf( o ))
  • 28. assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy
  • 29. assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy Always specify if you use Java or Groovy Truth
  • 30. assert “false” assert “ “ Object.asBoolean() Object => Boolean? Groovy : o asboolean Java : Boolean.valueOf( String.valueOf( o )) “false”, “null”: false in Java, true in Groovy Always specify if you use Java or Groovy Truth
  • 32. int j = ( o.size() > 0 ) ? o.size() : -1;
  • 33. int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 )
  • 34. int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?:defaultValue Takes defaultValue if value evaluates to false
  • 35. int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?:defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings
  • 36. int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?: defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings int j = ( size != null ) ? size : -1 int j = size ?: -1
  • 37. int j = ( o.size() > 0 ) ? o.size() : -1 def j = ( o.size() ?: -1 ) Elvis operator: def j = value ?: defaultValue Takes defaultValue if value evaluates to false Be careful with zero values and empty Strings int j = ( size != null ) ? size : -1 // Accepts zero size int j = size ?: -1 // Doesn’t accept zero size
  • 39. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); }
  • 40. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } Overload
  • 41. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. }
  • 42. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. }
  • 43. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. } def foo ( intj, int k = 1 ) { .. }
  • 44. public String foo( int j, int k ){ …} public String foo( int j ){ foo ( j, 1 ); } public String foo(){ foo ( 1, 1 ); } def foo ( int j = 1, int k = 1 ) { .. } def foo ( int j = 1, intk ) { .. } def foo ( intj, int k = 1 ) { .. } def foo ( int j = f1(), intk = f2()) { .. }
  • 46. public class Bean () { private int j; public intgetJ(){ return this.j; } public void setJ( int j ){ this.j = j; } }
  • 47. class Bean { int j } def b = new Bean() println ( b.j ) / println ( b.getJ()) b.j = 33 / b.setJ( 33 ) N Groovy beans can be kept in the same file
  • 49. def s = ‘aaaaaaa’
  • 50. def s = ‘aaaaaaa’ def s = ’’’aaaaaaaaabbbbbbbb’’’
  • 51. def s = ‘aaaaaaa’ def s = ’’’aaaaaaaaabbbbbbbb’’’ def s = “aaaaaaa” def s = ”””aaaaaaaaabbbbbbbb”””
  • 52. def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb”””
  • 53. def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb””” log.info ( String.format( “ .. %s .. ”, val )) log.info ( “ .. ${val} .. ” )
  • 54. def s = “aaaaaaa${b.j}” def s = ”””aaaa${ o.something() + b.j }aaaaabbbbbbbb””” assert "aaaaa".class == String assert "${1+2}".class == org.codehaus.groovy.runtime.GStringImpl
  • 56. if ( o == null ) { throw new RuntimeException( “msg” ) }
  • 57. if ( o == null ) { throw new RuntimeException( “msg” ) } assert o, “msg”
  • 58. if ( o == null ) { throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg”
  • 59. if ( o == null ) { throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message”
  • 60. if ( o == null ) { throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message” assert false, “Fatal error”
  • 61. if ( o == null ) { throw new RuntimeException( “msg” ) } assert o, “msg” assert ( o != null ), “msg” assert o, Long message” assert false, “Fatal error” Asserting code samples is a common practice
  • 62. def j = [1, 2] def k = [3, 4] assert j[0] == k[0]
  • 63. def j = [1, 2] def k = [3, 4] assert j[0] == k[0] Assertion failed: assert j[0] == k[0] || | || |1 | |3 | | [3, 4] | false [1, 2]
  • 64. GDK
  • 66. http://groovy.codehaus.org/groovy-jdk/ Java+++ Object String File Collection, Map, List, Set InputStream, OutputStream Reader, Writer
  • 67. Object/Collection/Map each() any(), every() find(), findAll(), grep() join() collect() min(), max(), sum() inject()
  • 68. String toURL() execute() eachLine() padLeft(), padRight() tr()
  • 69. File deleteDir() eachLine() eachFileRecurse() getText() write(String) traverse()
  • 70. Q&A