SlideShare a Scribd company logo
1 of 36
Groovy Closures
Java to Groovy
public class Demo
{
public static void main(String[] args)
{
for(int i = 0; i < 3; i++)
{
System.out.print("shipra" );
}
}
}
3.times { print 'Nexthoughts' }
Groovy Shell
1. Open a terminal window and type “groovysh”.
2. It allows easy access to evaluate Groovy expressions,
and run simple experiments.
Dynamic Typing Vs Static Typing
First, dynamically-typed languages perform type checking at
runtime, while statically typed languages perform type
checking at compile time.
This means that scripts written in dynamically-typed
languages (like Groovy) can compile even if they contain
errors that will prevent the script from running properly (if
at all). If a script written in a statically-typed language
(such as Java) contains errors, it will fail to compile until
the errors have been fixed.
// Java example
int num;
num = 5;
// Groovy example
num = 5
Groovy is dynamically-typed and determines its variables'
data types based on their values, so this line is not
required.
Strings
● Single Quoted
● Triple Single Quoted
● Double Quoted
● Triple Double Quoted
● Slashy
● Dollar Slashy
String summary table
Operator Overloading
Groovy supports operator overloading which makes working with
Numbers, Collections, Maps and various other data structures
easier to use.
def date = new Date()
date++
println date
All operators in Groovy are method calls.
The following few of the operators supported in Groovy and
the methods they map to
● a + b a.plus(b)
● a - b a.minus(b)
● a * b a.multiply(b)
● a ** b a.power(b)
● a / b a.div(b)
● a % b a.mod(b)
Groovy Truth
In Groovy you can use objects in if and while expressions.
A non-null and non-empty string will evaluate to true.
if("John" ) // any non-empty string is true
if(null) // null is false
if("" ) // empty strings are false
Non zero numbers will evaluate to true.
if(1) // any non-zero value is true
if(-1) // any non-zero value is true
if(0) // zero value is false
Groovy Truth For Collection
A non-empty collection will evaluate to true.
List family = ["John" , "Jane" ]
if(family) // true since the list is populated.
And Empty Collection will evaluate to false
List family = [ ]
if(family) // false since the map is not populated.
Groovy Classes
In Groovy Classes by default things are public unless you
specify otherwise.
Class Person {
String name
Integer age
}
Person person = new Person()
person.name = “Per
person.age =30
If you call person.name=”Groovy”
Then behind the scene
person.setName(“Groovy”)
If you want accidental modification in Groovy, you can add a
pair of getters and setters.
constructors
Person person = new Person(name:”Groovy”, age:20)
Person x = new Person()
Working with Files
new File("foo.txt").bytes
new File("foo.txt").readLines()
new File("foo.txt").eachLine { line -> println(line) }
Program structure
1. Package Name
2. Imports
a. Default Imports
b. Simple Imports
c. Star Imports
d. Static Imports
e. Static Star Imports
f. Import aliasing
g. Static Import aliasing
3. Something more and will cover later
Default import
import java.lang.*
import java.util.*
import java.io.*
import java.net.*
import groovy.lang.*
import groovy.util.*
import java.math.BigInteger
import java.math.BigDecimal
Static import
import static java.lang.String.format
class SomeClass {
String format(Integer i) {
i.toString()
}
static void main(String[] args) {
assert format('String') == 'String'
assert new SomeClass().format(Integer.valueOf(1)) == '1'
}
}
Import aliasing
import java.util.Date
import java.sql.Date as SQLDate
Date utilDate = new Date(1000L)
SQLDate sqlDate = new SQLDate(1000L)
assert utilDate instanceof java.util.Date
assert sqlDate instanceof java.sql.Date
Closures
1. A Closure is a block of code given a name.
2. Groovy has support for closures, which work much like
Java 8 lambdas. A closure is an anonymous block of
executable code.
3. Methods can accept closure as parameters.
4. Defining Closures
Syntax
1. Defining a closure
a. {[closureParameters->] statements}
2. Closure as an Object (An instance of groovy.lang.Closure)
a. def listener = {e-> println "Clicked on ${e}"}
3. Calling a closure
a. listener()
b. listener.call()
Parameters
1. Normal Parameters (with and without parameters)
2. Implicit Parameters
3. Varargs
Without Parameters
def helloWorld = {
println "Hello World"
}
Helloworld()
With Parameters
def power = { int x, int y ->
return Math.pow(x, y)
}
println power(2, 3)
Implicit parameter
When a closure does not explicitly define a parameter list
(using ->), a closure always defines an implicit parameter,
named it. This means that this code:
def greeting = { "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'
is strictly equivalent to this one:
def greeting = { it -> "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'
Implicit parameter
If you want to declare a closure which accepts no argument
and must be restricted to calls without arguments, then you
must declare it with an explicit empty argument list:
def magicNumber = { -> 42 }
// this call will fail because the closure doesn't accept any
argument
magicNumber(11)
varargs
It is possible for a closure to declare variable arguments
like any other method. Vargs methods are methods that can
accept a variable number of arguments if the last parameter
is of variable length (or an array) like in the next
examples:
def concat1 = { String... args -> args.join('') }
assert concat1('abc','def') == 'abcdef'
def concat2 = { String[] args -> args.join('') }
assert concat2('abc', 'def') == 'abcdef'
def multiConcat = { int n, String... args ->
args.join('')*n
}
assert multiConcat(2, 'abc','def') == 'abcdefabcdef'
Type definition of parameters is the same like variables. If
you define a type you can only use this type, but you can
also skip the type of parameters and pass in anything you
want
def say = { what ->
println what
}
say "Hello World"
Closures in gstrings
def x = 1
def gs = "x = ${x}"
assert gs == 'x = 1'
The code behaves as you would expect
but what happens If you add:
x = 2
assert gs == 'x = 2'
You will see that the assert fails! There are two reasons for
this:
a GString only evaluates lazily the toString representation
of values
the syntax ${x} in a GString does not represent a closure but
an expression to $x, evaluated when the GString is created.
If you need a real closure in a GString and for example
enforce lazy evaluation of variables, you need to use the
alternate syntax ${→ x} like in the fixed example:
def x = 1
def gs = "x = ${-> x}"
assert gs == 'x = 1'
x = 2
assert gs == 'x = 2'
Passing Closure
The power of being able to assign closures to variable is
that you can also pass them around to methods.
def transform = { str, transformation ->
transformation(str)
}
def myFun = { it.toUpperCase() }
println transform("Hello World", myFun)
class EvenNumberCalculations {
static main(args) {
def obj = new EvenNumberCalculations()
obj.printEvenNumbers(10)
def result = obj.calculateSumOfEvenNumbers(10);
println('Total: ' + result)
result = obj.calculateProductOfEvenNumbers(10);
println('Product: ' + result)
result = obj.calculateSquareOfEvenNumbers(10);
println('Squared: ' + result)
}
def printEvenNumbers(int n){
for(int i = 2; i <= n; i += 2) {
println(i)
}
}
int calculateSumOfEvenNumbers(int n){
def sum = 0;
for(int i = 2; i <= n; i += 2) {
sum += i
}
return sum;
}
int calculateProductOfEvenNumbers(int n){
def product = 1;
for(int i = 2; i <= n; i += 2) {
product *= i
}
return product;
}
int[] calculateSquareOfEvenNumbers(int n){
def squared = []
for(int i = 2; i <= n; i += 2) {
squared << i ** 2
}
return squared;
}
}
class EvenNumberCalculationsWithClosure {
static main(args) {
def obj = new EvenNumberCalculationsWithClosure()
obj.pickEvenNumbers(10, { println it })
def total = 0
obj.pickEvenNumbers(10) { total += it }
println('Total: ' + total)
def product = 1
obj.pickEvenNumbers(10) { product *= it }
println('Product: ' + product)
def squared = []
obj.pickEvenNumbers(10) { squared << it ** 2 }
println('Squared: ' + squared)
}
def pickEvenNumbers(n, block) {
for(int i = 2; i <= n; i += 2) {
block(i)
}
}
}

More Related Content

What's hot

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-CNissan Tsafrir
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Programming - Marla Fuentes
Programming - Marla FuentesProgramming - Marla Fuentes
Programming - Marla Fuentesmfuentessss
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problemRussell Childs
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeMitchell Tilbrook
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
JSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklJSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklChristoph Pickl
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object compositionVasyl Boroviak
 

What's hot (20)

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Clojure for Rubyists
Clojure for RubyistsClojure for Rubyists
Clojure for Rubyists
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Programming - Marla Fuentes
Programming - Marla FuentesProgramming - Marla Fuentes
Programming - Marla Fuentes
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React Native
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
JSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklJSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph Pickl
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object composition
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 

Similar to Groovy closures

Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In ScalaJoey Gibson
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
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 Wsloffenauer
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsJigar Gosar
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorialguligala
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 

Similar to Groovy closures (20)

Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Groovy!
Groovy!Groovy!
Groovy!
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Kotlin
KotlinKotlin
Kotlin
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Javascript
JavascriptJavascript
Javascript
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
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
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
 
Groovy
GroovyGroovy
Groovy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorial
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 

More from Vijay Shukla (20)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy
GroovyGroovy
Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
REST
RESTREST
REST
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Recently uploaded

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Groovy closures

  • 2. Java to Groovy public class Demo { public static void main(String[] args) { for(int i = 0; i < 3; i++) { System.out.print("shipra" ); } } }
  • 3. 3.times { print 'Nexthoughts' }
  • 4. Groovy Shell 1. Open a terminal window and type “groovysh”. 2. It allows easy access to evaluate Groovy expressions, and run simple experiments.
  • 5. Dynamic Typing Vs Static Typing First, dynamically-typed languages perform type checking at runtime, while statically typed languages perform type checking at compile time. This means that scripts written in dynamically-typed languages (like Groovy) can compile even if they contain errors that will prevent the script from running properly (if at all). If a script written in a statically-typed language (such as Java) contains errors, it will fail to compile until the errors have been fixed.
  • 6. // Java example int num; num = 5; // Groovy example num = 5 Groovy is dynamically-typed and determines its variables' data types based on their values, so this line is not required.
  • 7. Strings ● Single Quoted ● Triple Single Quoted ● Double Quoted ● Triple Double Quoted ● Slashy ● Dollar Slashy
  • 9. Operator Overloading Groovy supports operator overloading which makes working with Numbers, Collections, Maps and various other data structures easier to use. def date = new Date() date++ println date All operators in Groovy are method calls.
  • 10. The following few of the operators supported in Groovy and the methods they map to ● a + b a.plus(b) ● a - b a.minus(b) ● a * b a.multiply(b) ● a ** b a.power(b) ● a / b a.div(b) ● a % b a.mod(b)
  • 11. Groovy Truth In Groovy you can use objects in if and while expressions. A non-null and non-empty string will evaluate to true. if("John" ) // any non-empty string is true if(null) // null is false if("" ) // empty strings are false Non zero numbers will evaluate to true. if(1) // any non-zero value is true if(-1) // any non-zero value is true if(0) // zero value is false
  • 12. Groovy Truth For Collection A non-empty collection will evaluate to true. List family = ["John" , "Jane" ] if(family) // true since the list is populated. And Empty Collection will evaluate to false List family = [ ] if(family) // false since the map is not populated.
  • 13. Groovy Classes In Groovy Classes by default things are public unless you specify otherwise. Class Person { String name Integer age } Person person = new Person() person.name = “Per person.age =30
  • 14. If you call person.name=”Groovy” Then behind the scene person.setName(“Groovy”) If you want accidental modification in Groovy, you can add a pair of getters and setters.
  • 15. constructors Person person = new Person(name:”Groovy”, age:20) Person x = new Person()
  • 16. Working with Files new File("foo.txt").bytes new File("foo.txt").readLines() new File("foo.txt").eachLine { line -> println(line) }
  • 17. Program structure 1. Package Name 2. Imports a. Default Imports b. Simple Imports c. Star Imports d. Static Imports e. Static Star Imports f. Import aliasing g. Static Import aliasing 3. Something more and will cover later
  • 18. Default import import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal
  • 19. Static import import static java.lang.String.format class SomeClass { String format(Integer i) { i.toString() } static void main(String[] args) { assert format('String') == 'String' assert new SomeClass().format(Integer.valueOf(1)) == '1' } }
  • 20. Import aliasing import java.util.Date import java.sql.Date as SQLDate Date utilDate = new Date(1000L) SQLDate sqlDate = new SQLDate(1000L) assert utilDate instanceof java.util.Date assert sqlDate instanceof java.sql.Date
  • 21. Closures 1. A Closure is a block of code given a name. 2. Groovy has support for closures, which work much like Java 8 lambdas. A closure is an anonymous block of executable code. 3. Methods can accept closure as parameters. 4. Defining Closures
  • 22. Syntax 1. Defining a closure a. {[closureParameters->] statements} 2. Closure as an Object (An instance of groovy.lang.Closure) a. def listener = {e-> println "Clicked on ${e}"} 3. Calling a closure a. listener() b. listener.call()
  • 23. Parameters 1. Normal Parameters (with and without parameters) 2. Implicit Parameters 3. Varargs
  • 24. Without Parameters def helloWorld = { println "Hello World" } Helloworld() With Parameters def power = { int x, int y -> return Math.pow(x, y) } println power(2, 3)
  • 25. Implicit parameter When a closure does not explicitly define a parameter list (using ->), a closure always defines an implicit parameter, named it. This means that this code: def greeting = { "Hello, $it!" } assert greeting('Patrick') == 'Hello, Patrick!' is strictly equivalent to this one: def greeting = { it -> "Hello, $it!" } assert greeting('Patrick') == 'Hello, Patrick!'
  • 26. Implicit parameter If you want to declare a closure which accepts no argument and must be restricted to calls without arguments, then you must declare it with an explicit empty argument list: def magicNumber = { -> 42 } // this call will fail because the closure doesn't accept any argument magicNumber(11)
  • 27. varargs It is possible for a closure to declare variable arguments like any other method. Vargs methods are methods that can accept a variable number of arguments if the last parameter is of variable length (or an array) like in the next examples: def concat1 = { String... args -> args.join('') } assert concat1('abc','def') == 'abcdef'
  • 28. def concat2 = { String[] args -> args.join('') } assert concat2('abc', 'def') == 'abcdef' def multiConcat = { int n, String... args -> args.join('')*n } assert multiConcat(2, 'abc','def') == 'abcdefabcdef'
  • 29. Type definition of parameters is the same like variables. If you define a type you can only use this type, but you can also skip the type of parameters and pass in anything you want def say = { what -> println what } say "Hello World"
  • 30. Closures in gstrings def x = 1 def gs = "x = ${x}" assert gs == 'x = 1' The code behaves as you would expect
  • 31. but what happens If you add: x = 2 assert gs == 'x = 2'
  • 32. You will see that the assert fails! There are two reasons for this: a GString only evaluates lazily the toString representation of values the syntax ${x} in a GString does not represent a closure but an expression to $x, evaluated when the GString is created.
  • 33. If you need a real closure in a GString and for example enforce lazy evaluation of variables, you need to use the alternate syntax ${→ x} like in the fixed example: def x = 1 def gs = "x = ${-> x}" assert gs == 'x = 1' x = 2 assert gs == 'x = 2'
  • 34. Passing Closure The power of being able to assign closures to variable is that you can also pass them around to methods. def transform = { str, transformation -> transformation(str) } def myFun = { it.toUpperCase() } println transform("Hello World", myFun)
  • 35. class EvenNumberCalculations { static main(args) { def obj = new EvenNumberCalculations() obj.printEvenNumbers(10) def result = obj.calculateSumOfEvenNumbers(10); println('Total: ' + result) result = obj.calculateProductOfEvenNumbers(10); println('Product: ' + result) result = obj.calculateSquareOfEvenNumbers(10); println('Squared: ' + result) } def printEvenNumbers(int n){ for(int i = 2; i <= n; i += 2) { println(i) } } int calculateSumOfEvenNumbers(int n){ def sum = 0; for(int i = 2; i <= n; i += 2) { sum += i } return sum; } int calculateProductOfEvenNumbers(int n){ def product = 1; for(int i = 2; i <= n; i += 2) { product *= i } return product; } int[] calculateSquareOfEvenNumbers(int n){ def squared = [] for(int i = 2; i <= n; i += 2) { squared << i ** 2 } return squared; } }
  • 36. class EvenNumberCalculationsWithClosure { static main(args) { def obj = new EvenNumberCalculationsWithClosure() obj.pickEvenNumbers(10, { println it }) def total = 0 obj.pickEvenNumbers(10) { total += it } println('Total: ' + total) def product = 1 obj.pickEvenNumbers(10) { product *= it } println('Product: ' + product) def squared = [] obj.pickEvenNumbers(10) { squared << it ** 2 } println('Squared: ' + squared) } def pickEvenNumbers(n, block) { for(int i = 2; i <= n; i += 2) { block(i) } } }