SlideShare a Scribd company logo
1 of 31
Groovy
Agenda
1. Installation
2. Difference with JAVA
3. Groovy Development Kit
4. Syntax
5. Operators
6. Groovy Truth
7. Program Structure (later)
8. Closures
Installation
Differences with JAVA
● Default Imports
● Multi-Methods
● Array Initializers
● GStrings and String and Character Literals
● Primitives and Wrappers
● Behavior of ==
● Extra Keywords
Default Imports
Multi-Methods/Runtime-Dispatch
In Groovy
int method(String arg) {
return 1;
}
int method(Object arg) {
return 2;
}
Object o = "Object";
int result = method(o);
assert 1==result
In Java
int method(String arg) {
return 1;
}
int method(Object arg) {
return 2;
}
Object o = "Object";
int result = method(o);
assertEquals(2,result)
Array Initializers
GStringsand String and Character Literals
Singly quoted literals in Groovy are used for Strings, and double quoted result in
String as well as GString.
● assert 'c'.getClass()==String
● assert "c".getClass()==String
● assert "c${1}".getClass() in GString
When calling methods with argument of type char we need to either cast explicitly
or make sure the value has been cast in advance.
Groovy Casting can be done by two ways:-
● assert ((char) "c").class==Character
● assert ("c" as char).class==Character
For multi char String:-
● assert ((char) 'cx') == 'c' // GroovyCast Exception
● assert ('cx' as char) == 'c'
● assert 'cx'.asType(char) == 'c'
Primitive and Wrappers
Groovy autowraps references to primitives.
Behaviour of ==
In java == means equality of primitive types or identity for objects.
In groovy == translates to a.compareTo(b)==0, if they are comparable and
a.equals(b) otherwise.
To check Identity we had a.is(b)
● Comments
○ Single Line Comments
○ Multi-line Comments
○ GroovyDoc Comments
● Keywords
○ as
○ def
○ in
○ trait
● Identifier
○ All keywords are also valid identifiers when following a dot. (foo.as)
○ Quoted Identifiers
Quoted Identifier
String
1. Single quoted
2. Double quoted
3. Triple Single quoted
4. Triple Double Quoted
Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Conditional Operators
5. Object Operators
Elvis Operator(?:)
Safe Navigation Operator(?.)
Method Pointer Operator (.&)
Spread Operator (*.)
Range Operator (..)
Spaceship Operator (<==>) delegates to compareTo
MemberShip Operator (in)
User Field Access Operator (.@)
http://www.groovy-lang.org/operators.html#_other_operators
Groovy Collections
Data structure that helps in dealing with a number of objects.
A wide variety of methods available for easy manipulation.
List
A list cares about the index
Elements are assigned indices on the basis of how they are added
Has methods related to the index
Index starts from 0
Creating list
//create empty list with each element of type 'def'
List list = [ ]
//create empty list with elements of type 'type'
List<type> list = [ ]
List<type> list = new ArrayList()
Adding an element
list.add(“element1”)
list << “element1”
list += “element1”
list.push(element)
List firstList = [1,2,3,4,5]
List secondList = [“element2”]
List thirdList = firstList + secondList
println thirdList // [1,2,3,4,5,”element2”]
fourthlist = thirdlist - firstlist
println fourthlist // [“element2”]
Fetching elements:
list[i] – Get ith element in list starting from 0
list.get(0) – Get first element in list
list.getAt(0) – Get first element in list
list.first() - Get first element of list
list.head() - Get the head of list
list.last() - Get last element of list
list.tail() - Get all elements except first
list.getAt(1..10) – Get elements from index 1 to 10
(includes index 10)
list.subList(1, 10) - Get elements at index 1 to 10 (index
10 excluded)
Removing duplicates from a List :
list.unique() // Alters original list
list as Set
Deleting an element from a List :
(All of them alter original list)
list.remove(idx)
list.pop()
list.removeAll(collection)
Convert String into List:
“Hi” as List / “Hi”.toList()
string.tokenize('_') : Splits the string into a list with argument used as delimiter.
string.split('_') : Same as tokenize but can also accept regular expressions as
delimiters
Convert List into String:
list.join(',')
Operations on each element of list:
println list*.name // Use of spread operator
list.collect { it.multiply(2) } // what if 'it' refers to string?
list.find { it.name==”abc” } // returns one object
list.findAll { it.name==”abc” } // returns list
list.each { println it.name }
list.eachWithIndex{p, index ->
println index +”. “ + p.name
}
list.reverseEach { println it.name }
List Methods
size() - Get size of list
reverse() - reverses the order of list elements
contains(value) – Find if list contains specified value
sum(closure) - Sum all the elements of the list
min(closure) – Get min value of list
max(closure) – Get max value of list
flatten() - Make nested lists into a simple list
sort(closure) - Sort the list in ascending order
.list1.intersect(list2) : returns a list that contains elements that exist in both the
lists.
.list1.disjoint(list2) : Returns true/false indicating whether lists are disjoint
or not.
.every{condition} : checks whether every element of the list satisfy the
condition.
.any{condition} : checks whether any of the element of the satisfy the
condition.
Set
A Set cares about uniqueness - it doesn't allow duplicates
It can be considered as a list with restrictions, and is often constructed from a
list.
Set set = [1,3,3,4] as Set
([1,3,4])
No Ordering; element positions do not matter
Most methods available to lists, besides those that don't make sense for
unordered items, are available to sets.
Like - getAt, putAt, reverse
Ranges
Ranges allow you to create a list of sequential values.
These can be used as Lists since Range extends java.util.List.
Generally used for looping, switch, lists etc
Ranges defined with the “..” notation are inclusive (that is the list contains the
from and to value).
Ranges defined with the “..<” notation are exclusive, they include the first value but
not the last value.
Range range = 1..10
range = -10..<10
range = '#'..'~'
Methods
range.from – Get the lower limit of range
range.to – Get upper limit of range
range.contains(value) – Does range contain value?
1. Groovy Truth (later)
2. Program Structure (later)
3. Closures(later)

More Related Content

What's hot

Python Dictionary
Python DictionaryPython Dictionary
Python DictionarySoba Arjun
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Python dictionary
Python dictionaryPython dictionary
Python dictionaryeman lotfy
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplAnkur Shrivastava
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_pythondeepalishinkar1
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collectionsPrem Kumar Badri
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Exp 6.2 d-422 (1)
Exp 6.2  d-422 (1)Exp 6.2  d-422 (1)
Exp 6.2 d-422 (1)Omkar Rane
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.Harsh Mathur
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List ComprehensionsYos Riady
 

What's hot (19)

Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
List in Python
List in PythonList in Python
List in Python
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collections
 
Python list
Python listPython list
Python list
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Exp 6.2 d-422 (1)
Exp 6.2  d-422 (1)Exp 6.2  d-422 (1)
Exp 6.2 d-422 (1)
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 

Similar to Groovy

1 list datastructures
1 list datastructures1 list datastructures
1 list datastructuresNguync91368
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfmayorothenguyenhob69
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonCeline George
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
Introduction of Python-1.pdf
Introduction of Python-1.pdfIntroduction of Python-1.pdf
Introduction of Python-1.pdfSyamsulFattanSSos
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 

Similar to Groovy (20)

Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
강의자료6
강의자료6강의자료6
강의자료6
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Kotlin 101 Workshop
Kotlin 101 WorkshopKotlin 101 Workshop
Kotlin 101 Workshop
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
Introduction of Python-1.pdf
Introduction of Python-1.pdfIntroduction of Python-1.pdf
Introduction of Python-1.pdf
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
collections
collectionscollections
collections
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 

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 closures
Groovy closuresGroovy closures
Groovy closures
 
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

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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
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
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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 pragmaticsAndrey Dotsenko
 
"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
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
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
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
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
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
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
 
"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
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
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...
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Groovy

  • 2. Agenda 1. Installation 2. Difference with JAVA 3. Groovy Development Kit 4. Syntax 5. Operators 6. Groovy Truth 7. Program Structure (later) 8. Closures
  • 4. Differences with JAVA ● Default Imports ● Multi-Methods ● Array Initializers ● GStrings and String and Character Literals ● Primitives and Wrappers ● Behavior of == ● Extra Keywords
  • 6. Multi-Methods/Runtime-Dispatch In Groovy int method(String arg) { return 1; } int method(Object arg) { return 2; } Object o = "Object"; int result = method(o); assert 1==result In Java int method(String arg) { return 1; } int method(Object arg) { return 2; } Object o = "Object"; int result = method(o); assertEquals(2,result)
  • 8. GStringsand String and Character Literals Singly quoted literals in Groovy are used for Strings, and double quoted result in String as well as GString. ● assert 'c'.getClass()==String ● assert "c".getClass()==String ● assert "c${1}".getClass() in GString When calling methods with argument of type char we need to either cast explicitly or make sure the value has been cast in advance.
  • 9. Groovy Casting can be done by two ways:- ● assert ((char) "c").class==Character ● assert ("c" as char).class==Character For multi char String:- ● assert ((char) 'cx') == 'c' // GroovyCast Exception ● assert ('cx' as char) == 'c' ● assert 'cx'.asType(char) == 'c'
  • 10. Primitive and Wrappers Groovy autowraps references to primitives.
  • 11. Behaviour of == In java == means equality of primitive types or identity for objects. In groovy == translates to a.compareTo(b)==0, if they are comparable and a.equals(b) otherwise. To check Identity we had a.is(b)
  • 12. ● Comments ○ Single Line Comments ○ Multi-line Comments ○ GroovyDoc Comments ● Keywords ○ as ○ def ○ in ○ trait ● Identifier ○ All keywords are also valid identifiers when following a dot. (foo.as) ○ Quoted Identifiers
  • 14. String 1. Single quoted 2. Double quoted 3. Triple Single quoted 4. Triple Double Quoted
  • 15. Operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Conditional Operators 5. Object Operators
  • 16. Elvis Operator(?:) Safe Navigation Operator(?.) Method Pointer Operator (.&) Spread Operator (*.) Range Operator (..) Spaceship Operator (<==>) delegates to compareTo MemberShip Operator (in) User Field Access Operator (.@) http://www.groovy-lang.org/operators.html#_other_operators
  • 17.
  • 18. Groovy Collections Data structure that helps in dealing with a number of objects. A wide variety of methods available for easy manipulation.
  • 19. List A list cares about the index Elements are assigned indices on the basis of how they are added Has methods related to the index Index starts from 0 Creating list //create empty list with each element of type 'def' List list = [ ] //create empty list with elements of type 'type' List<type> list = [ ] List<type> list = new ArrayList()
  • 20. Adding an element list.add(“element1”) list << “element1” list += “element1” list.push(element) List firstList = [1,2,3,4,5] List secondList = [“element2”] List thirdList = firstList + secondList println thirdList // [1,2,3,4,5,”element2”] fourthlist = thirdlist - firstlist println fourthlist // [“element2”]
  • 21. Fetching elements: list[i] – Get ith element in list starting from 0 list.get(0) – Get first element in list list.getAt(0) – Get first element in list list.first() - Get first element of list list.head() - Get the head of list list.last() - Get last element of list list.tail() - Get all elements except first list.getAt(1..10) – Get elements from index 1 to 10 (includes index 10) list.subList(1, 10) - Get elements at index 1 to 10 (index 10 excluded)
  • 22. Removing duplicates from a List : list.unique() // Alters original list list as Set Deleting an element from a List : (All of them alter original list) list.remove(idx) list.pop() list.removeAll(collection)
  • 23. Convert String into List: “Hi” as List / “Hi”.toList() string.tokenize('_') : Splits the string into a list with argument used as delimiter. string.split('_') : Same as tokenize but can also accept regular expressions as delimiters Convert List into String: list.join(',')
  • 24. Operations on each element of list: println list*.name // Use of spread operator list.collect { it.multiply(2) } // what if 'it' refers to string? list.find { it.name==”abc” } // returns one object list.findAll { it.name==”abc” } // returns list list.each { println it.name } list.eachWithIndex{p, index -> println index +”. “ + p.name } list.reverseEach { println it.name }
  • 25. List Methods size() - Get size of list reverse() - reverses the order of list elements contains(value) – Find if list contains specified value sum(closure) - Sum all the elements of the list min(closure) – Get min value of list max(closure) – Get max value of list flatten() - Make nested lists into a simple list sort(closure) - Sort the list in ascending order
  • 26. .list1.intersect(list2) : returns a list that contains elements that exist in both the lists. .list1.disjoint(list2) : Returns true/false indicating whether lists are disjoint or not. .every{condition} : checks whether every element of the list satisfy the condition. .any{condition} : checks whether any of the element of the satisfy the condition.
  • 27. Set A Set cares about uniqueness - it doesn't allow duplicates It can be considered as a list with restrictions, and is often constructed from a list. Set set = [1,3,3,4] as Set ([1,3,4]) No Ordering; element positions do not matter
  • 28. Most methods available to lists, besides those that don't make sense for unordered items, are available to sets. Like - getAt, putAt, reverse
  • 29. Ranges Ranges allow you to create a list of sequential values. These can be used as Lists since Range extends java.util.List. Generally used for looping, switch, lists etc Ranges defined with the “..” notation are inclusive (that is the list contains the from and to value). Ranges defined with the “..<” notation are exclusive, they include the first value but not the last value.
  • 30. Range range = 1..10 range = -10..<10 range = '#'..'~' Methods range.from – Get the lower limit of range range.to – Get upper limit of range range.contains(value) – Does range contain value?
  • 31. 1. Groovy Truth (later) 2. Program Structure (later) 3. Closures(later)