introduction to groovy (serbian developer conference 2013)

40
An Introduction to Groovy Coding Serbia, 17.10.2013 Joachim Baumann

Upload: joachim-baumann

Post on 22-Jan-2015

323 views

Category:

Technology


1 download

DESCRIPTION

An introduction to Groovy

TRANSCRIPT

  • 1. An Introduction to Groovy Coding Serbia, 17.10.2013 Joachim Baumann

2. Agenda Tour de Force The Language Use Cases Everything is an Object Collections: Ranges, Lists and Maps Control Structures Operator OverloadingClosures: Higher-Order FunctionsCategories: Extending Classes at RuntimeExamples 3. Groovy Is a Scripting Language Regular Programming LanguageIs derived from JavaIs a dynamic languageIs ofcially dened in the Java Community Process JSR-241 (Java Specication Request)Is executed on a standard Java Virtual Machine Exists since 2003 (It is de facto an old language) Is in the Top 20 list of TIOBE Current version is 2.1.8 4. An Example (Java) public class HelloWorld { public static void main(String [ ] args) { System.out.println(HelloWorld); } }The Simplest existing Java Program 5. An Example (Groovy)println Hello WorldHello WorldComment: The example on the previous page is correct Groovy code also 6. Use Cases Programming of Scripts instead of Sh, Perl, Python, Ruby Unit-Tests Much simpler way of writing test cases Direct support for stub and mock objectsFull-blown Applications Frameworks Grails as a Web-Application Framework Griffon as a Swing-Application FrameworkIntegration in large Applications As Glue Code Class-by-Class Substitution for Java e.g. in Spring As Conguration Language As Domain-Specic Language 7. Language Features Very similar to Java Easy to learn In fact, every Java Program is a valid Groovy program Java Object Model is used Groovy tries to follow the principle of least surprise All Java classes and frameworks can be used High number of existing frameworks Translated Groovy classes can be used by Java Integration in both directions Typing Strong or weak Dynamic or static 8. Everything is an Object Java differentiates primitive data types and objects Original motivation were performance problems Leads to impedance mismatch translate problemsIn Groovy everything is an Object Numbers are objects as well5.times { println Hallo Welt }Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt 9. Explicit Typing is optional Duck Typing Known from Scripting languagesSimplies ProgrammingWe do not need to provide the type of a variableUnder the hood Groovy uses explicit Typingdef a = 1a is of Type Integer (simplified) 10. Collections Groovy adds a new Collection Type RangeAnd adds a lot of syntactic sugar for existing Collection Types Lists MapsFurthermore, the interfaces are harmonized Example Method size() 11. Collections: Range (a special variant of List) Dene a number of elements (a range) in an interval 1..5Inclusive: Range 1 - 5 Ranges are Objects def r = 1.. println n }1 2 3 4 Elements are only created on demand Classes implementing the Interface Comparable and providing the methods next() und previous(), can be used in Ranges. 12. Collections: Lists Simplied Notation (extends the Java-Type List)def list = [1, 2] Adding and Removing Valueslist += 3 list = list - [2] We can iterate over the elementslist.each { n -> println n } [1, 2, 3] [1, 3]1 3Subscript operator is supported (as with Ranges) 13. Collections: Maps Simplied Notation ( extends the Java-Type Map)def map = [ name: Groovy, typ: Language ] Accessing Elementsmap.each { entry -> println $entry.key: $entry.value} map [name] = English Shortened Accessprintln map.nameEnglishname: Groovy typ: Language 14. Control StructuresNew For Loop Syntaxfor ( i in 1..5 ) println Hello $iHello 1 Hello 2 Hello 3 Hello 4 Hello 5Every normal Java control structure is supported (including For Loops)Boolean decision much more general through the use of Groovy Truth Coercion of Collections, Iterators, Enumerations, Maps, Matchers, Strings, Numbers and Object References to a boolean expression 15. Control Structures: Switch Statement Switch much more general than Java (Example with Type, Range and Closure)switch ( val ) { case { it > 3 }: println $val is larger than 3; break case 5..9:println $val is in the Range 5 9; breakcase Number: println $val is of Type Number ; break } 16. Operator-Overloading(1) Impossible in JavaWidely used in GroovyProvided for many existing Java classesWorks by implementing the respective Method Example Operator + Operator Method plus() Method minus()Thus your own implementations are straightforward 17. Operator Overloading(2) class Complex { BigDecimal r BigDecimal i def plus (Complex c) { new Complex (r : this.r + c.r, i : this.i + c.i) } } def res = new Complex(r:1, i:-1) + new Complex (r:1, i:1) println "$res.r + $res.i i" 2+0i 18. Closures: Higher-Order Functions Basic Idea: Methods are Objects Known from functional programming There we have rst-order (and higher-order) functionsAnonymous inner classes on SteroidsUsage Separation of Concerns Separation of Iteration and Logic Central Resource Handling Functional Programming Approaches 19. Closures: Denition (1) We have met (anonymous) Closures alreadymap.each { entry -> println $entry.key: $entry.value} case { it > 3 }: println $val is larger than 3General Denitiondef c = { p1, p2, p3 = 0 -> [ Source of the Closure] }Parameters can accept Default Values If no Parameter is given, then Implicit Parameter it Return Value is the Result of the last statement 20. Closures: Example def square = { x -> x * x } 4println square(2) r = 1..5 r.each { println square(it) }1 4 9 16 25def cubed = { x -> x * square (x) } r.each { println cubed(it) } Implicit Parameter it1 8 27 64 125 21. Closures: Functional Programming (1) Denition In mathematics and computer science, currying is the technique of transforming a function that takes multiple arguments (or a tuple of arguments) in such a way that it can be called as a chain of functions, each with a single argument (partial application). It was originated by Moses Schnnkel and later re-discovered by Haskell Curry. Because of this, some say it would be more correct to name it schnnkeling. WikipediaFixes the number of arguments to a function, thereby generating a new functionAllows the concatenation of functions 22. Closures: Functional Programming (2)def mul = { x, y -> x * y } def mul2 = mul.curry(2) def mul5 = mul.curry(5) println mul2(3) println mul5(2)Equals { y -> 2 * y } Equals { y -> 5 * y } 6 10def komp = { g, f, x -> g( f(x) ) } def mul10 = komp.curry(mul2, mul5) println mul10(5) // Left Shift Operator mul10 = mul2 println "$elem.title, $elem.artist" }The Output The 59th Street Bridge Song, Simon and Garfunkel Monday Monday, The Mamas and The Papas Goodnight Moon, Shivaree Suddenly, SorayaGPath Expression 27. Example: WebServer (25 Lines) def webPath = args[0] def getPattern = /GET (/?[^? ]*)??([^ ]+)?s+HTTP/[.d]+/ def server = new ServerSocket(5926) while(true) { server.accept() { socket -> socket.withStreams { input, output -> def line, resource def reader = input.newReader() while(line = reader.readLine()) { println line def match = line =~ getPattern if(match) resource = match[0][1] } def f = new File ("$webPath/$resource") if(f.directory) f = "$webPath/$resource/index.html" as File if(!f.exists()) f = "$webPath/error.html" as File}output