SlideShare a Scribd company logo
Groovy on Android
Pascal Nsue Engonga
2015
Agenda
● What is Groovy?
● Syntax(Closure. Array/Map. GString and
other features).
● Pros and cons of using Groovy.
● AST.
● SwissKnife.
Joke #0
When Android developers get java 8?
What is the Groovy?
● Is an agile and dynamic language for the Java Virtual Machine
● Builds upon the strengths of Java but has additional power features inspired by languages like Python,
Ruby and Smalltalk
● Makes modern programming features available to Java developers with almost-zero learning curve
● Provides the ability to statically type check and statically compile your code for robustness and
performance
● Supports Domain-Specific Languages and other compact syntax so your code becomes easy to read
and maintain
● Makes writing shell and build scripts easy with its powerful processing primitives
● Simplifies testing by supporting unit testing and mocking out-of-the-box
● Seamlessly integrates with all existing Java classes and libraries
● Compiles straight to Java bytecode so you can use it anywhere you can use Java
Usage
Polling
Keywords
as assert break case
catch class const continue
def default do else
enum extends false finally
for goto if implements
import in instanceof interface
new null package return
super switch this throw
throws trait true try
while
Groovy Features
Joke #1
Closure
Closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and
be assigned to a variable.
● { item++ }
● { -> item++ }
● { println it }
● { it -> println it }
● { name -> println name }
● { String x, int y ->
println "hey ${x} the value is ${y}"
}
● { reader ->
def line = reader.readLine()
line.trim()
}
GString
//Now you can ref to a variable in string
def name = 'Guillaume' // a plain string
def greeting = "Hello $name"
assert greeting.toString() == 'Hello Guillaume'
//Or even do some operations
def sum = "The sum of 2 and 3 equals ${2 + 3}"
assert sum.toString() == 'The sum of 2 and 3 equals 5'
Map/List
def list = [5, 6, 7, 8]
assert list.get(2) == 7
assert list[2] == 7
def map = [name: 'Gromit', likes: 'cheese', id: 1234]
def emptyMap = [:]
assert map.get('name') == 'Gromit'
assert map.get('id') == 1234
assert map['name'] == 'Gromit'
assert map['id'] == 1234
Range
def range = 5..8
assert range.size() == 4
assert range.get(2) == 7
assert range[2] == 7
assert range instanceof java.util.List
assert range.contains(5)
// lets use a half-open range
range = 5..<8
assert range.from == 5
assert range.to == 8
Safe navigation & Elvis operator
def person = Person.find { it.id == 123 }
def firstChar = person?.name?.charAt(0)
assert name == null
displayName = user.name ? user.name : 'Anonymous'
displayName = user.name ?: 'Anonymous'
Spread operator
class Car {
String make
String model
}
def cars = [
new Car(make: 'Peugeot', model: '508'),
new Car(make: 'Renault', model: 'Clio')]
def makes = cars*.make
assert makes == ['Peugeot', 'Renault']
Regular expression operators
//has it’s own literal
def p = ~/foo/
assert p instanceof Pattern
//Example
def text = "some text to match"
def m = text =~ /match/
assert m instanceof Matcher
if (!m) {
throw new RuntimeException("Oops, text not found!")
}
Method pointer operator
def transform(List elements, Closure action) {
def result = []
elements.each {
result << action(it)
}
result
}
String describe(Person p) {
"$p.name is $p.age"
}
def action = this.&describe
def list = [
new Person(name: 'Bob', age: 42),
new Person(name: 'Julia', age: 35)]
assert transform(list, action) == ['Bob is 42', 'Julia is 35']
Operator overloading
Operator Method Operator Method
+ a.plus(b) a[b] a.getAt(b)
- a.minus(b) a[b] = c a.putAt(b, c)
* a.multiply(b) << a.leftShift(b)
/ a.div(b) >> a.rightShift(b)
% a.mod(b) ++ a.next()
** a.power(b) -- a.previous()
| a.or(b) +a a.positive()
& a.and(b) -a a.negative()
^ a.xor(b) ~a a.bitwiseNegative()
Sequence operations
'qwerty'.each {print it}
('a'..'z').each {print it}
('a'..'z').findAll { el -> // = filter
el in ['e', 'y', 'u', 'i', 'o', 'a']
}.each {
print it + ' '}
(0..10).collect { el -> // = map
el * 10
}.each {print it + ' '}
Working with I/O
//Adds helper methods for files
new File(baseDir, 'haiku.txt').eachLine { line ->
println line
}
//Easy to work InputStream
new File(baseDir,'haiku.txt').withInputStream { stream ->...
}
//And Writers
new File(baseDir,'haiku.txt').withWriter('utf-8') { writer ->
writer.writeLine 'Into the ancient pond'
writer.writeLine 'A frog jumps'
writer.writeLine 'Water’s sound!'
}
//get bytes
byte[] contents = file.bytes
AST
@TupleConstructor
@EqualsAndHashCode
@ToString for beans
@Canonical
@Sortable for beans
@Memoize for methods
Slupper
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText '''
{ "simple": 123,
"fraction": 123.66,
"exponential": 123e12
}'''
assert object instanceof Map
assert object.simple.class == Integer
assert object.fraction.class == BigDecimal
assert object.exponential.class == BigDecimal
Dynamic vs Static
Groovy 2.0
without
@CompileStatic
Groovy/Java
performance
factor
Groovy 2.0
with
@CompileStatic
Groovy/Java
performance
factor
Kotlin
0.1.2580
Java
static ternary 4352ms 4.7 926ms 1.0 1005ms 924ms
static if 4267ms 4.7 911ms 0.9 1828ms 917ms
instance ternary 4577ms 2.7 1681ms 1.8 994ms 917ms
instance if 4592ms 2.9 1604ms 1.7 1611ms
969ms
@CompileStatic
SwissKnife
Based on both ButterKnife and AndroidAnnotations.
● Inject views like butterknife add callback methods @OnClick, @OnItemClick
● Execute methods in the UI Thread or a background one using @OnUIThread
and @OnBackground.
● Make your variables persistent across state changes without
messing with onSaveInstanceState().
● Make anything Parcelable with the @Parcelable annotation - which
can be used with @SaveInstance to automatize data persistance.
● Read intent extras automatically with @Extra annotation.
Q&A
Literature
● Groovy in Action
● http://docs.groovy-lang.org/
● Making Java Groovy
● Groovy programming: an introduction for Java
developers
Thanks!!!!!

More Related Content

What's hot

C++ tutorial
C++ tutorialC++ tutorial
Groovy
GroovyGroovy
Groovy
Zen Urban
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 
Docopt
DocoptDocopt
Docopt
René Ribaud
 
Sol9
Sol9Sol9
Отладка в GDB
Отладка в GDBОтладка в GDB
Отладка в GDB
Anthony Shoumikhin
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
Alipay
 
Vim Hacks (OSSF)
Vim Hacks (OSSF)Vim Hacks (OSSF)
Vim Hacks (OSSF)
Lin Yo-An
 
Thread介紹
Thread介紹Thread介紹
Thread介紹
Jack Chen
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
Piotr Lewandowski
 
Tools.cpp
Tools.cppTools.cpp
Tools.cpp
Vorname Nachname
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
Sunscrapers
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
akaptur
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
Romain Francois
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
Larry Diehl
 

What's hot (19)

C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Groovy
GroovyGroovy
Groovy
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Docopt
DocoptDocopt
Docopt
 
Sol9
Sol9Sol9
Sol9
 
Отладка в GDB
Отладка в GDBОтладка в GDB
Отладка в GDB
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
 
Vim Hacks (OSSF)
Vim Hacks (OSSF)Vim Hacks (OSSF)
Vim Hacks (OSSF)
 
Thread介紹
Thread介紹Thread介紹
Thread介紹
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Tools.cpp
Tools.cppTools.cpp
Tools.cpp
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 

Similar to Groovy

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad
 
Groovy!
Groovy!Groovy!
Groovy!
Petr Giecek
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
manishkp84
 
Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
Giancarlo Frison
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
Lei Kang
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
Hiroshi SHIBATA
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
Matt Passell
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014
Damien Seguy
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
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
loffenauer
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Through
niklal
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
Andres Almiray
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why not
ChengHui Weng
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 

Similar to Groovy (20)

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Groovy!
Groovy!Groovy!
Groovy!
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Introduction To Groovy
Introduction To GroovyIntroduction To Groovy
Introduction To Groovy
 
Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
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
 
Groovy Fly Through
Groovy Fly ThroughGroovy Fly Through
Groovy Fly Through
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why not
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 

Recently uploaded

Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 

Recently uploaded (20)

Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 

Groovy

  • 1. Groovy on Android Pascal Nsue Engonga 2015
  • 2. Agenda ● What is Groovy? ● Syntax(Closure. Array/Map. GString and other features). ● Pros and cons of using Groovy. ● AST. ● SwissKnife.
  • 3. Joke #0 When Android developers get java 8?
  • 4. What is the Groovy? ● Is an agile and dynamic language for the Java Virtual Machine ● Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk ● Makes modern programming features available to Java developers with almost-zero learning curve ● Provides the ability to statically type check and statically compile your code for robustness and performance ● Supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain ● Makes writing shell and build scripts easy with its powerful processing primitives ● Simplifies testing by supporting unit testing and mocking out-of-the-box ● Seamlessly integrates with all existing Java classes and libraries ● Compiles straight to Java bytecode so you can use it anywhere you can use Java
  • 7. Keywords as assert break case catch class const continue def default do else enum extends false finally for goto if implements import in instanceof interface new null package return super switch this throw throws trait true try while
  • 10. Closure Closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. ● { item++ } ● { -> item++ } ● { println it } ● { it -> println it } ● { name -> println name } ● { String x, int y -> println "hey ${x} the value is ${y}" } ● { reader -> def line = reader.readLine() line.trim() }
  • 11. GString //Now you can ref to a variable in string def name = 'Guillaume' // a plain string def greeting = "Hello $name" assert greeting.toString() == 'Hello Guillaume' //Or even do some operations def sum = "The sum of 2 and 3 equals ${2 + 3}" assert sum.toString() == 'The sum of 2 and 3 equals 5'
  • 12. Map/List def list = [5, 6, 7, 8] assert list.get(2) == 7 assert list[2] == 7 def map = [name: 'Gromit', likes: 'cheese', id: 1234] def emptyMap = [:] assert map.get('name') == 'Gromit' assert map.get('id') == 1234 assert map['name'] == 'Gromit' assert map['id'] == 1234
  • 13. Range def range = 5..8 assert range.size() == 4 assert range.get(2) == 7 assert range[2] == 7 assert range instanceof java.util.List assert range.contains(5) // lets use a half-open range range = 5..<8 assert range.from == 5 assert range.to == 8
  • 14. Safe navigation & Elvis operator def person = Person.find { it.id == 123 } def firstChar = person?.name?.charAt(0) assert name == null displayName = user.name ? user.name : 'Anonymous' displayName = user.name ?: 'Anonymous'
  • 15. Spread operator class Car { String make String model } def cars = [ new Car(make: 'Peugeot', model: '508'), new Car(make: 'Renault', model: 'Clio')] def makes = cars*.make assert makes == ['Peugeot', 'Renault']
  • 16. Regular expression operators //has it’s own literal def p = ~/foo/ assert p instanceof Pattern //Example def text = "some text to match" def m = text =~ /match/ assert m instanceof Matcher if (!m) { throw new RuntimeException("Oops, text not found!") }
  • 17. Method pointer operator def transform(List elements, Closure action) { def result = [] elements.each { result << action(it) } result } String describe(Person p) { "$p.name is $p.age" } def action = this.&describe def list = [ new Person(name: 'Bob', age: 42), new Person(name: 'Julia', age: 35)] assert transform(list, action) == ['Bob is 42', 'Julia is 35']
  • 18. Operator overloading Operator Method Operator Method + a.plus(b) a[b] a.getAt(b) - a.minus(b) a[b] = c a.putAt(b, c) * a.multiply(b) << a.leftShift(b) / a.div(b) >> a.rightShift(b) % a.mod(b) ++ a.next() ** a.power(b) -- a.previous() | a.or(b) +a a.positive() & a.and(b) -a a.negative() ^ a.xor(b) ~a a.bitwiseNegative()
  • 19. Sequence operations 'qwerty'.each {print it} ('a'..'z').each {print it} ('a'..'z').findAll { el -> // = filter el in ['e', 'y', 'u', 'i', 'o', 'a'] }.each { print it + ' '} (0..10).collect { el -> // = map el * 10 }.each {print it + ' '}
  • 20. Working with I/O //Adds helper methods for files new File(baseDir, 'haiku.txt').eachLine { line -> println line } //Easy to work InputStream new File(baseDir,'haiku.txt').withInputStream { stream ->... } //And Writers new File(baseDir,'haiku.txt').withWriter('utf-8') { writer -> writer.writeLine 'Into the ancient pond' writer.writeLine 'A frog jumps' writer.writeLine 'Water’s sound!' } //get bytes byte[] contents = file.bytes
  • 22. Slupper def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText ''' { "simple": 123, "fraction": 123.66, "exponential": 123e12 }''' assert object instanceof Map assert object.simple.class == Integer assert object.fraction.class == BigDecimal assert object.exponential.class == BigDecimal
  • 23. Dynamic vs Static Groovy 2.0 without @CompileStatic Groovy/Java performance factor Groovy 2.0 with @CompileStatic Groovy/Java performance factor Kotlin 0.1.2580 Java static ternary 4352ms 4.7 926ms 1.0 1005ms 924ms static if 4267ms 4.7 911ms 0.9 1828ms 917ms instance ternary 4577ms 2.7 1681ms 1.8 994ms 917ms instance if 4592ms 2.9 1604ms 1.7 1611ms 969ms @CompileStatic
  • 24. SwissKnife Based on both ButterKnife and AndroidAnnotations. ● Inject views like butterknife add callback methods @OnClick, @OnItemClick ● Execute methods in the UI Thread or a background one using @OnUIThread and @OnBackground. ● Make your variables persistent across state changes without messing with onSaveInstanceState(). ● Make anything Parcelable with the @Parcelable annotation - which can be used with @SaveInstance to automatize data persistance. ● Read intent extras automatically with @Extra annotation.
  • 25. Q&A
  • 26. Literature ● Groovy in Action ● http://docs.groovy-lang.org/ ● Making Java Groovy ● Groovy programming: an introduction for Java developers