SlideShare a Scribd company logo
Groovy APIQIYI AD TeamYan Lei
You can define a variable without specifying TYPEdef user = new User()You can define function argumentswithout TYPEvoid testUser(user) { user.shout() }Types in Groovy1.1.getClass().name  // java.math.BigDecimalMultimethordsExampleDynamic Type
import java.util.*;public class UsingCollection{public static void main(String[] args){ArrayList<String> lst = new ArrayList<String>();Collection<String> col = lst;lst.add("one" );lst.add("two" );lst.add("three" );lst.remove(0);col.remove(0);System.out.println("Added three items, remove two, so 1 item to remain." );System.out.println("Number of elements is: " + lst.size());System.out.println("Number of elements is: " + col.size());}}ExamplePlease Give Result running on Java & Groovy
One of The biggest contributions of GDK is extending the JDK with methods that take closures.Define a closuredef closure = { println “hello world”}ExampledefpickEven(n, block){for(inti = 2; i <= n; i += 2){	block(i)}}pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argumentdef Total = 0; pickEvent(10) {total += it}; println total Using Closures
When you curry( ) a closure, you’re asking the parameters to be prebound.ExampledeftellFortunes(closure){Date date = new Date("11/15/2007" )postFortune= closure.curry(date)postFortune "Your day is filled with ceremony"postFortune "They're features, not bugs"}tellFortunes() { date, fortune ->println"Fortune for ${date} is '${fortune}'"}Curried Closure
def examine(closure){println "$closure.maximumNumberOfParameters parameter(s) given:"for(aParameter in closure.parameterTypes) { println aParameter.name }}examine() { }  // 1, Objectexamine() { it } // 1, Objectexamine() {-> } // 0examine() { val1 -> } // 1, Objectexamine() {Date val1 -> } // 1, Dateexamine() {Date val1, val2 -> } // 2, Date, Objectexamine() {Date val1, String val2 -> } // 2, Date, StringDynamic Closures
Three properties of a closure determine which object handles a method call from within a closure. These are this, owner, and delegate. Generally, the delegate is set to owner, but changing it allows you to exploit Groovy for some really good metaprogramming capabilities.Example ??? Closure Delegation
Creating String with ‘,  “(GStringImpl), ‘’’(multiLine) getSubString using [] , “hello”[3], “hello”[1..3]As String in Java, String in Groovy is immutable.Working with String
Problemprice = 568.23company = 'Google'quote = "Today $company stock closed at $price"println quotestocks = [Apple : 130.01, Microsoft : 35.95]stocks.each { key, value ->company = keyprice = valueprintln quote}Why ? When you defined the GString—quote—you bound the variables company and price to a String holding the value Google and an Integer holding that obscene stock price, respectively. You can change the company and price references all you want (both of these are referring to  immutable objects) to refer to other objects, but you’re not changing what the GString instance has been bound to.SolutionUsing closurequote = “Today ${->company} stock closed at ${->price}”GString Lazy Evaluation Problem
“hello world” -= “world” for(str in ‘abc’..’abz’){ print “${str} ”}Regular ExpressionsDefine pattern :  def pattern = ~”[aAbB]”Matching=~ , ==~“Groovy is good” =~ /g|Groovy/  //match“Groovy is good” ==~ /g|Groovy/  //no match('Groovy is groovy, really groovy'=~ /groovy/).replaceAll(‘good' )String Convenience Methods
def a = [1,2,3,4,5,6,7] // ArrayListDef b = a[2..5] // b is an object of RandomAccessSubListUsing each for iterating over an lista.each { println it }Finder Methords: find & findAlla.find {it > 6} //7 return the first match resulta.findAll {it > 5} //[5,7] return a list include all matched membersConvenience Methodcollectinjectjoinflatten*List
def a = [s:1,d:2,f:3] //LinkedHashMapfetch value by Key: a.s, a[“s”]a.each {entry -> println “$entry.key : $entry.value” }a.each{key, value -> println“$key : $value” }MethodsCollect, find, findAllAny, everygroupByMap
The dump and inspect Methodsdump( ) lets you take a peek into an object.Println“hello”.dump()java.lang.String@5e918d2 value=[h, e, l, l, o] offset=0 count=5 hash=99162322Groovy also adds another method, inspect( ), to Object. This method is intended to tell you what input would be needed to create an object. If unimplemented on a class, it simply returns what toString( ) returns. If your object takes extensive input, this method will help users of your class figure out at runtime what input they should provide.Object Extensions
identity: The Context Methodlst = [1, 2]lst.identity {add(3)add(4)println size() //4println contains(2) // trueprintln "this is ${this}," //this is Identity@ce56f8,println "owner is ${owner}," //owner is Identity@ce56f8,println "delegate is ${delegate}." //delegate is [1, 2, 3, 4].}Object Extensions
Sleep: suppresses the Interrupted-Exception. If you do care to be interrupted, you don’t have to endure try-catch. Instead, in Groovy, you can use a variation of the previous sleep( ) method that accepts a closure to handle the interruption.new Object().sleep(2000) {println "Interrupted... " + itflag //if false, the thread will sleep 2 second as if there is no interruption}Object Extensions
class Car{int miles, fuelLevelvoid run(){println “boom …”}Void status(int a, String b) {println“$a --- $b”}}car = new Car(fuelLevel: 80, miles: 25)Indirect Property Accessprintln car[“miles”]Indirect Method Invokecar.invokeMethod(“status”, [1,”a”] as Object[])Object Extensions
Overloaded operators for Character, Integer, and so on. Such as plus( ) for operator +, next( ) for operator++, and so on.Number (which Integer and Double extend) has picked up the iterator methods upto( ) and downto( ). It also has the step( ) method.Thread.start{} & Thread.startDaemon()java.lang extensions
Read fileprintln new File('thoreau.txt' ).textnew File('thoreau.txt' ).eachLine { line ->println line}println new File('thoreau.txt' ).filterLine { it =~ /life/ }Write filenew File("output.txt" ).withWriter{ file ->	file << "some data..."}java.io Extensions
Details about calling a methodGroovy Object
Use MetaClass to modify a class at runtimeDynamic Adding or modifying MethodA.metaclass.newMethod= { println “new method”}Dynamic Adding or modifying variableA.metaClass.newParam = 1After these, U cannew A().newMethod()println new A().newParamMetaClass
Implements GroovyInterceptable & define method invokeMethod(String name, args)Using MetaClassdefine a closure for metaclassCar.metaClass.invokeMethod = { String name, args->//…}Intercepting Methods
Ad

More Related Content

What's hot (20)

Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
Matt Passell
 
Knolx session
Knolx sessionKnolx session
Knolx session
Knoldus Inc.
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Brian Moschel
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
Prajwala Manchikatla
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
Norman Richards
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
Norman Richards
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
John De Goes
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
John De Goes
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
Ibrahim Kasim
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
彥彬 洪
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
Matt Passell
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Brian Moschel
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
Norman Richards
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
John De Goes
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
John De Goes
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
Ibrahim Kasim
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
彥彬 洪
 

Similar to Groovy Api Tutorial (20)

Groovy
GroovyGroovy
Groovy
Zen Urban
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
HamletDRC
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
zhang tao
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
application developer
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
GR8Conf
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
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 closures
Groovy closuresGroovy closures
Groovy closures
Vijay Shukla
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
Ted Leung
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
Ducat India
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Alf Kristian Støyle
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
Ali Tanwir
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
HamletDRC
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
zhang tao
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
GR8Conf
 
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
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
Ted Leung
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
Ali Tanwir
 
Ad

Groovy Api Tutorial

  • 1. Groovy APIQIYI AD TeamYan Lei
  • 2. You can define a variable without specifying TYPEdef user = new User()You can define function argumentswithout TYPEvoid testUser(user) { user.shout() }Types in Groovy1.1.getClass().name // java.math.BigDecimalMultimethordsExampleDynamic Type
  • 3. import java.util.*;public class UsingCollection{public static void main(String[] args){ArrayList<String> lst = new ArrayList<String>();Collection<String> col = lst;lst.add("one" );lst.add("two" );lst.add("three" );lst.remove(0);col.remove(0);System.out.println("Added three items, remove two, so 1 item to remain." );System.out.println("Number of elements is: " + lst.size());System.out.println("Number of elements is: " + col.size());}}ExamplePlease Give Result running on Java & Groovy
  • 4. One of The biggest contributions of GDK is extending the JDK with methods that take closures.Define a closuredef closure = { println “hello world”}ExampledefpickEven(n, block){for(inti = 2; i <= n; i += 2){ block(i)}}pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argumentdef Total = 0; pickEvent(10) {total += it}; println total Using Closures
  • 5. When you curry( ) a closure, you’re asking the parameters to be prebound.ExampledeftellFortunes(closure){Date date = new Date("11/15/2007" )postFortune= closure.curry(date)postFortune "Your day is filled with ceremony"postFortune "They're features, not bugs"}tellFortunes() { date, fortune ->println"Fortune for ${date} is '${fortune}'"}Curried Closure
  • 6. def examine(closure){println "$closure.maximumNumberOfParameters parameter(s) given:"for(aParameter in closure.parameterTypes) { println aParameter.name }}examine() { } // 1, Objectexamine() { it } // 1, Objectexamine() {-> } // 0examine() { val1 -> } // 1, Objectexamine() {Date val1 -> } // 1, Dateexamine() {Date val1, val2 -> } // 2, Date, Objectexamine() {Date val1, String val2 -> } // 2, Date, StringDynamic Closures
  • 7. Three properties of a closure determine which object handles a method call from within a closure. These are this, owner, and delegate. Generally, the delegate is set to owner, but changing it allows you to exploit Groovy for some really good metaprogramming capabilities.Example ??? Closure Delegation
  • 8. Creating String with ‘, “(GStringImpl), ‘’’(multiLine) getSubString using [] , “hello”[3], “hello”[1..3]As String in Java, String in Groovy is immutable.Working with String
  • 9. Problemprice = 568.23company = 'Google'quote = "Today $company stock closed at $price"println quotestocks = [Apple : 130.01, Microsoft : 35.95]stocks.each { key, value ->company = keyprice = valueprintln quote}Why ? When you defined the GString—quote—you bound the variables company and price to a String holding the value Google and an Integer holding that obscene stock price, respectively. You can change the company and price references all you want (both of these are referring to immutable objects) to refer to other objects, but you’re not changing what the GString instance has been bound to.SolutionUsing closurequote = “Today ${->company} stock closed at ${->price}”GString Lazy Evaluation Problem
  • 10. “hello world” -= “world” for(str in ‘abc’..’abz’){ print “${str} ”}Regular ExpressionsDefine pattern : def pattern = ~”[aAbB]”Matching=~ , ==~“Groovy is good” =~ /g|Groovy/ //match“Groovy is good” ==~ /g|Groovy/ //no match('Groovy is groovy, really groovy'=~ /groovy/).replaceAll(‘good' )String Convenience Methods
  • 11. def a = [1,2,3,4,5,6,7] // ArrayListDef b = a[2..5] // b is an object of RandomAccessSubListUsing each for iterating over an lista.each { println it }Finder Methords: find & findAlla.find {it > 6} //7 return the first match resulta.findAll {it > 5} //[5,7] return a list include all matched membersConvenience Methodcollectinjectjoinflatten*List
  • 12. def a = [s:1,d:2,f:3] //LinkedHashMapfetch value by Key: a.s, a[“s”]a.each {entry -> println “$entry.key : $entry.value” }a.each{key, value -> println“$key : $value” }MethodsCollect, find, findAllAny, everygroupByMap
  • 13. The dump and inspect Methodsdump( ) lets you take a peek into an object.Println“hello”.dump()java.lang.String@5e918d2 value=[h, e, l, l, o] offset=0 count=5 hash=99162322Groovy also adds another method, inspect( ), to Object. This method is intended to tell you what input would be needed to create an object. If unimplemented on a class, it simply returns what toString( ) returns. If your object takes extensive input, this method will help users of your class figure out at runtime what input they should provide.Object Extensions
  • 14. identity: The Context Methodlst = [1, 2]lst.identity {add(3)add(4)println size() //4println contains(2) // trueprintln "this is ${this}," //this is Identity@ce56f8,println "owner is ${owner}," //owner is Identity@ce56f8,println "delegate is ${delegate}." //delegate is [1, 2, 3, 4].}Object Extensions
  • 15. Sleep: suppresses the Interrupted-Exception. If you do care to be interrupted, you don’t have to endure try-catch. Instead, in Groovy, you can use a variation of the previous sleep( ) method that accepts a closure to handle the interruption.new Object().sleep(2000) {println "Interrupted... " + itflag //if false, the thread will sleep 2 second as if there is no interruption}Object Extensions
  • 16. class Car{int miles, fuelLevelvoid run(){println “boom …”}Void status(int a, String b) {println“$a --- $b”}}car = new Car(fuelLevel: 80, miles: 25)Indirect Property Accessprintln car[“miles”]Indirect Method Invokecar.invokeMethod(“status”, [1,”a”] as Object[])Object Extensions
  • 17. Overloaded operators for Character, Integer, and so on. Such as plus( ) for operator +, next( ) for operator++, and so on.Number (which Integer and Double extend) has picked up the iterator methods upto( ) and downto( ). It also has the step( ) method.Thread.start{} & Thread.startDaemon()java.lang extensions
  • 18. Read fileprintln new File('thoreau.txt' ).textnew File('thoreau.txt' ).eachLine { line ->println line}println new File('thoreau.txt' ).filterLine { it =~ /life/ }Write filenew File("output.txt" ).withWriter{ file -> file << "some data..."}java.io Extensions
  • 19. Details about calling a methodGroovy Object
  • 20. Use MetaClass to modify a class at runtimeDynamic Adding or modifying MethodA.metaclass.newMethod= { println “new method”}Dynamic Adding or modifying variableA.metaClass.newParam = 1After these, U cannew A().newMethod()println new A().newParamMetaClass
  • 21. Implements GroovyInterceptable & define method invokeMethod(String name, args)Using MetaClassdefine a closure for metaclassCar.metaClass.invokeMethod = { String name, args->//…}Intercepting Methods

Editor's Notes

  • #11: defhaha = &quot;haha&quot;def a = /asdasdas ${haha}/printlnhaha.getClass().nameprintlna.getClass().nameprintln &quot;haha&quot;[1..3]defnum = &quot;012345678&quot;printlnnum[-1 .. 0]for(str in &apos;abc&apos;..&apos;abz&apos;){ print &quot;$str &quot;}