SlideShare a Scribd company logo
1 of 21
Groovy API QIYI AD Team Yan Lei
You can define a variable without specifying TYPE def user = new User() You can define function argumentswithout TYPE void testUser(user) { user.shout() } Types in Groovy 1.1.getClass().name  // java.math.BigDecimal Multimethords Example Dynamic 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()); } } Example Please Give Result running on Java & Groovy
One of The biggest contributions of GDK is extending the JDK with methods that take closures. Define a closure def closure = { println “hello world”} Example defpickEven(n, block){ for(inti = 2; i <= n; i += 2){ 	block(i) } } pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argument def Total = 0; pickEvent(10) {total += it}; println total  Using Closures
When you curry( ) a closure, you’re asking the parameters to be prebound. Example deftellFortunes(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, Object examine() { it } // 1, Object examine() {-> } // 0 examine() { val1 -> } // 1, Object examine() {Date val1 -> } // 1, Date examine() {Date val1, val2 -> } // 2, Date, Object examine() {Date val1, String val2 -> } // 2, Date, String Dynamic 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
Problem price = 568.23 company = 'Google' quote = "Today $company stock closed at $price" println quote stocks = [Apple : 130.01, Microsoft : 35.95] stocks.each { key, value -> company = key price = value println 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. Solution Using closure quote = “Today ${->company} stock closed at ${->price}” GString Lazy Evaluation Problem
“hello world” -= “world”  for(str in ‘abc’..’abz’){ print “${str} ”} Regular Expressions Define 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] // ArrayList Def b = a[2..5] // b is an object of RandomAccessSubList Using each for iterating over an list a.each { println it } Finder Methords: find & findAll a.find {it > 6} //7 return the first match result a.findAll {it > 5} //[5,7] return a list include all matched members Convenience Method collect inject join flatten * List
def a = [s:1,d:2,f:3] //LinkedHashMap fetch value by Key: a.s, a[“s”] a.each {entry -> println “$entry.key : $entry.value” } a.each{key, value -> println“$key : $value” } Methods Collect, find, findAll Any, every groupBy Map
The dump and inspect Methods dump( ) 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=99162322 Groovy 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 Method lst = [1, 2] lst.identity { add(3) add(4) println size() //4 println contains(2) // true println "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... " + it flag //if false, the thread will sleep 2 second as if there is no interruption } Object Extensions
class Car{ int miles, fuelLevel void run(){println “boom …”} Void status(int a, String b) {println“$a --- $b”} } car = new Car(fuelLevel: 80, miles: 25) Indirect Property Access println car[“miles”] Indirect Method Invoke car.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 file println new File('thoreau.txt' ).text new File('thoreau.txt' ).eachLine { line ->println line} println new File('thoreau.txt' ).filterLine { it =~ /life/ } Write file new File("output.txt" ).withWriter{ file -> 	file << "some data..." } java.io Extensions
Details about calling a method Groovy Object
Use MetaClass to modify a class at runtime Dynamic Adding or modifying Method A.metaclass.newMethod= { println “new method”} Dynamic Adding or modifying variable A.metaClass.newParam = 1 After these, U can new A().newMethod() println new A().newParam MetaClass
Implements GroovyInterceptable & define method invokeMethod(String name, args) Using MetaClass define a closure for metaclass Car.metaClass.invokeMethod = { String name, args-> //… } Intercepting Methods

More Related Content

What's hot

Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type ConversionsRokonuzzaman Rony
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin 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 FunctionsBrian 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 unificationNorman Richards
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQKnoldus Inc.
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn 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 BossBob Tiernay
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in pythonIbrahim Kasim
 
科特林λ學
科特林λ學科特林λ學
科特林λ學彥彬 洪
 

What's hot (20)

Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
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)
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
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
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
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!
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
 
科特林λ學
科特林λ學科特林λ學
科特林λ學
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Lecture5
Lecture5Lecture5
Lecture5
 

Similar to Groovy Api Tutorial

Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang 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
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
 
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
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovyTed Leung
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with GroovyAli Tanwir
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introductiongosain20
 

Similar to Groovy Api Tutorial (20)

Groovy
GroovyGroovy
Groovy
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
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 closures
Groovy closuresGroovy closures
Groovy closures
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
Kotlin
KotlinKotlin
Kotlin
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
 

Groovy Api Tutorial

  • 1. Groovy API QIYI AD Team Yan Lei
  • 2. You can define a variable without specifying TYPE def user = new User() You can define function argumentswithout TYPE void testUser(user) { user.shout() } Types in Groovy 1.1.getClass().name // java.math.BigDecimal Multimethords Example Dynamic 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()); } } Example Please 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 closure def closure = { println “hello world”} Example defpickEven(n, block){ for(inti = 2; i <= n; i += 2){ block(i) } } pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argument def Total = 0; pickEvent(10) {total += it}; println total Using Closures
  • 5. When you curry( ) a closure, you’re asking the parameters to be prebound. Example deftellFortunes(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, Object examine() { it } // 1, Object examine() {-> } // 0 examine() { val1 -> } // 1, Object examine() {Date val1 -> } // 1, Date examine() {Date val1, val2 -> } // 2, Date, Object examine() {Date val1, String val2 -> } // 2, Date, String Dynamic 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. Problem price = 568.23 company = 'Google' quote = "Today $company stock closed at $price" println quote stocks = [Apple : 130.01, Microsoft : 35.95] stocks.each { key, value -> company = key price = value println 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. Solution Using closure quote = “Today ${->company} stock closed at ${->price}” GString Lazy Evaluation Problem
  • 10. “hello world” -= “world” for(str in ‘abc’..’abz’){ print “${str} ”} Regular Expressions Define 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] // ArrayList Def b = a[2..5] // b is an object of RandomAccessSubList Using each for iterating over an list a.each { println it } Finder Methords: find & findAll a.find {it > 6} //7 return the first match result a.findAll {it > 5} //[5,7] return a list include all matched members Convenience Method collect inject join flatten * List
  • 12. def a = [s:1,d:2,f:3] //LinkedHashMap fetch value by Key: a.s, a[“s”] a.each {entry -> println “$entry.key : $entry.value” } a.each{key, value -> println“$key : $value” } Methods Collect, find, findAll Any, every groupBy Map
  • 13. The dump and inspect Methods dump( ) 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=99162322 Groovy 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 Method lst = [1, 2] lst.identity { add(3) add(4) println size() //4 println contains(2) // true println "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... " + it flag //if false, the thread will sleep 2 second as if there is no interruption } Object Extensions
  • 16. class Car{ int miles, fuelLevel void run(){println “boom …”} Void status(int a, String b) {println“$a --- $b”} } car = new Car(fuelLevel: 80, miles: 25) Indirect Property Access println car[“miles”] Indirect Method Invoke car.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 file println new File('thoreau.txt' ).text new File('thoreau.txt' ).eachLine { line ->println line} println new File('thoreau.txt' ).filterLine { it =~ /life/ } Write file new File("output.txt" ).withWriter{ file -> file << "some data..." } java.io Extensions
  • 19. Details about calling a method Groovy Object
  • 20. Use MetaClass to modify a class at runtime Dynamic Adding or modifying Method A.metaclass.newMethod= { println “new method”} Dynamic Adding or modifying variable A.metaClass.newParam = 1 After these, U can new A().newMethod() println new A().newParam MetaClass
  • 21. Implements GroovyInterceptable & define method invokeMethod(String name, args) Using MetaClass define a closure for metaclass Car.metaClass.invokeMethod = { String name, args-> //… } Intercepting Methods

Editor's Notes

  1. 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;}