Your SlideShare is downloading. ×
  • Like
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply



Groovy speech I held last year for introducing a new JVM language as substitute of Java. Easy and intuitive, it offers new features unknow to its parent yet.

Groovy speech I held last year for introducing a new JVM language as substitute of Java. Easy and intuitive, it offers new features unknow to its parent yet.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. Groovy OverviewIt is Java as it should be. Easy and intuitive, itoffers new features unknown to its parent yet,and come up with those benefits that form thebasis of the DSLsGiancarlo Frison
  • 2. Groovy is a super vision of Java. It can leverage Java’s enterprisecapabilities but also has closures and dynamic typing, without allceremonial syntax needed in Java● Introduction● Data types● Language features● Closures● Meta programming
  • 3. What is Groovy?
  • 4. Introduction Groovy = Java – boiler plate code + mostly dynamic typing + closures + domain specific languages
  • 5. Groovy Overview● Fully Object oriented ● Gpath expressions● Closures: reusable and ● Grep and switch assignable piece of code ● Builders (XML, Json, Swing,● Groovy Beans Ant, Tests)● Collection Literals (lists, ● Additional operators (? Null maps, ranges, regular safe) expressions) ● Default and named● Meta programming (MOP, arguments Expando, AST ● String enhances transformations, ● Osgi Mixins/Categories)
  • 6. Frameworks● Grails Web framework inspired by Ruby on Rails● Gradle The next generation build system● Griffon Desktop framework inspired by Grails● Grape Add dependencies to your classpath● Gorm Grails ORM persistance framework● Gpars Concurrency/parallelism library
  • 7. Less tedious syntax
  • 8. A better Java…
  • 9. …a better Java…
  • 10. …a better Java…
  • 11. …a better Java…
  • 12. …a better Java…
  • 13. …a better Java…
  • 14. …a better Java…
  • 15. …a better Java.
  • 16. Better JavaBeans…
  • 17. …a better JavaBeans…
  • 18. …a better JavaBeans.
  • 19. Data Types
  • 20. GStrings● Multi-line strings ● Rangesdef tt = assert fullname[0..5] == name She sells, sea shells By the sea shore‘ ● Comparison operators a==b a +-* b● String interpolation a<=>b a[]def fullname = “$name $surname” ● Groovy-gdk● Regexs http://groovy.codehaus.assert-36==~ ‘/^[+-]?d+$/’ org/groovy- jdk/java/lang/String.html
  • 21. Collections● Literal syntax ● Overloading operatorslist = [3,new Date(),’Jan] list << new Date()assert list + list == list * 2 ● Loop closures map.each{key, value -> println “$key : $value”● Maps }map = [a:1,b:2]assert map[a]==1 && map.b ==2 ● …loop closures each, every, collect, any, inject, find, findAll,upto,● Ranges downto, times, grep, reverseEach, eachMatch,def ls = ‘a..z‘,nums = 0..<10 eachWithIndex, eachLineassert ls.size+nums.size == 36 eachFile, eachFileMatch…
  • 22. Math operations● No more :BigDecimal.divide(BigDecimal right, <scale>, BigDecimal.ROUND_HALF_UP)● Insteadassert 1/2 == new java.math.BigDecimal("0.5")
  • 23. Datesuse ( groovy.time.TimeCategory ) { println println 10.hours.ago println new Date() - 3.months def duration = date1 - date2 println "days: ${duration.days}, Hours: ${duration.hours}"}
  • 24. Language Features
  • 25. Improved Switch● It can handle any kind of valueswitch (x) { case James: break case 18..65: break case ~/Gw?+e/: break case Date: break case [John, Ringo, Paul, George]: break default:}
  • 26. Groovy Truth● Any expression could be used and evaluated whereas Java requires a boolean.● Number 0 return false● Empty string, lists, maps, matchers return false● Null objects return false● Of course… boolean false return false
  • 27. Null Object Pattern● Null-safe version of Javas . operatorpeople << new Person(name:Harry)biggestSalary = people.collect{ p -> p.job?.salary }.max()println biggestSalary
  • 28. Named argumentssend(String from, String to, String subject, String body) { println "sender ${from}" println "sender ${to}" println "sender ${subject}" println "sender ${body}"}send from:"", to:"", subject:"greetings", body:"Hello Goodbye"
  • 29. Multiple assignmentsdef (a, b, c) = [10, 20, foo]assert a == 10 && b == 20 && c == foo‘def geocode(String location) { // implementation returns [48.824068, 2.531733]}def (lat, long) = geocode(“Bassano del Grappa, Italia")
  • 30. GPath● expression language integrated into Groovy which allows parts of nested structured data to be identified. ● a.b.c -> for XML, yields all the <c> elements inside <b> inside <a>def feed = new XmlSlurper().parse([0].title ● a.b.c -> all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a.getB().getC() in JavaBeans)
  • 31. Closures
  • 32. Closures● Treats data structures and operations as Objectsdef clos = { println "hello!" }clos()● Closures as method argumentsdef houston = {doit -> (10..1).each{ count-> doit(count) }}houston{ println it }
  • 33. Closure delegate● Groovy has 3 variables inside each closure for defining different classes in his scope: ● this: As in Java it refers to the closure itself. ● owner: Enclosing object of the closure. ● delegate: The same of the owner, but it can be replaced● When a closure encounters a method call that it cannot handle itself, it automatically relays the invocation to its owner object. If this fails, it relays the invocation to its delegate.
  • 34. Closures for better design…
  • 35. …more better design.
  • 36. Meta Object Programming
  • 37. Groovy MOP● Runtime ● Compile-time● ExpandoMetaClass ● AST Transformations● Closures● Categories
  • 38. ExpandoMetaClass● Allow to dynamically add methods, properties…String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ?Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString()}println "hELLO wORLD".swapCase()
  • 39. Expando● It is a container for everything added by developerdef bean = new Expando( name:"James", location:"London", id:123 )assert "James" == bean.nameassert 123 ==
  • 40. Categories● Add functionalities to classes to make them more usableclass StringCategory { static String lower(String string) { return string.toLowerCase() }}use (StringCategory) { assert "test" == "TeSt".lower()}use (groovy.time.TimeCategory ) { println println 10.hours.ago println new Date() - 3.months}
  • 41. AST Examples● Grape@Grab(org.mortbay.jetty:jetty-embedded:6.1.0)def server = new Server(8080)println "Starting Jetty, press Ctrl+C to stop."server.start()● Slf4j@Slf4jclass HelloWorld { def logHello() { Hello World }}
  • 42. AST Transformations● compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty.● Global transformations adding a jar● Local transformations by annotating code elements:@Immutable @Delegate @Log @Field @PackageScope @AutoClone@AutoExternalizable @ThreadInterrupt @TimedInterrupt@ConditionalInterrupt @ToString @EqualsAndHashCode@TupleConstructor @Canonical @InheritConstructors @WithReadLock@WithWriteLock @ListenerList @Singleton @Lazy @Newify @Category@Mixin @PackageScope @Grab @Bindable @Vetoable
  • 43. …and Happy coding! Questions?Giancarlo Frison -