{"id":19594015,"url":"https://github.com/jonatan-ivanov/groovy-training","last_synced_at":"2025-10-28T23:02:53.222Z","repository":{"id":150733419,"uuid":"77721655","full_name":"jonatan-ivanov/groovy-training","owner":"jonatan-ivanov","description":"An old training that I held about Groovy","archived":false,"fork":false,"pushed_at":"2021-05-09T03:46:04.000Z","size":18,"stargazers_count":5,"open_issues_count":0,"forks_count":1,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-06-07T23:58:16.563Z","etag":null,"topics":["demo","groovy","jvm"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jonatan-ivanov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-12-31T02:40:08.000Z","updated_at":"2021-05-09T03:46:06.000Z","dependencies_parsed_at":null,"dependency_job_id":"4ed618b9-94a7-4ee7-92f9-b34ee8693f56","html_url":"https://github.com/jonatan-ivanov/groovy-training","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jonatan-ivanov/groovy-training","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonatan-ivanov%2Fgroovy-training","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonatan-ivanov%2Fgroovy-training/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonatan-ivanov%2Fgroovy-training/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonatan-ivanov%2Fgroovy-training/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jonatan-ivanov","download_url":"https://codeload.github.com/jonatan-ivanov/groovy-training/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonatan-ivanov%2Fgroovy-training/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259964327,"owners_count":22938724,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["demo","groovy","jvm"],"created_at":"2024-11-11T08:42:04.329Z","updated_at":"2025-10-28T23:02:53.168Z","avatar_url":"https://github.com/jonatan-ivanov.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Groovy - A dynamic language for the Java platform\nAn old training that I held about Groovy, please check the code examples.  \nCould be outdated (especially the links).\n\n# Foundation - Facts, Advantages, Disadvantages\r\n## Facts\r\n- Founded in late 2003\r\n- Runs on JVM (compiles to Java bytecode)\r\n- Optional typing (runtime type checking, binding)\r\n- Complements Java (dynamic capabilities)\r\n- Most popular language on the JVM after Java (?) (based on the old Groovy documentation page)\r\n- [http://www.groovy-lang.org/](http://www.groovy-lang.org/)\n\n## Advantages\r\n- Optional typing\r\n- Additional powerful features (later)\r\n    - Function literals/closures (see Java 8 lambda expressions)\n    - Cool operators, extensions\n    - Native support for\n        - Collections\n        - Regular Expressions\n        - XML processing\n- Supports DSLs\r\n- Can be used as a scripting language (parse, compile, generate, execute on JVM)\r\n- You can write Java as Groovy (Java-like syntax)\r\n- Flat learning curve\r\n- Excellent rapid prototyping language\r\n- Simplified testing (supports unit testing and mocking OOB)\r\n- IDE support (Eclipse, IntelliJ, NetBeans)\r\n- GroovyConsole\n- (demo: 001\\_Hello\\_World, 002\\_Zero)\r\n\n## Disadvantages\r\n- IDE support could be better\r\n- Code checking/analysis/metrics etc. could be hard or impossible  \n    (Checkstyle, PMD, Code Coverage)\r\n- Performance  \n    `GroovyObject#invokeMethod(String name, Object.. args)`  \r\n    reflection, lookups, proxies  \r\n    \u003c=\u003e invokedynamic (Java 7+, Groovy 2.1+)\r\n- Optional typing (?)\r\n- Free syntax (?)\r\n\n# Groovy 101 - It's Groovy baby, yeah! (Austin Powers)\n## Usage\r\n- Java-like installation and usage\n    - `GROOVY_HOME` ~ `JAVA_HOME`\n    - `groovyc` ~ `javac`\n    - `groovy` ~ `java`\n    - `.groovy` ~ `.java`\n- The Runtime can call `groovyc` (source must be on the *classpath*)\r\n- `groovy -e \"println 12.5 * Math.PI\"`\r\n- `groovysh` - Groovy Shell\r\n- `groovyConsole`\r\n- `java2groovy`\n\n## Syntax differences\r\n- Not required\r\n    - Semicolons at the end of the statements\n    - `return` statements\n    - Parentheses for method parameters\n- `public` is the default access modifier (class, field, method)\r\n- Auto-generated ctors, getters and setters\r\n- Script: outside of Class\r\n\r\n## Default imports\r\n```\ngroovy.lang.*\r\ngroovy.util.*\r\njava.lang.*\r\njava.io.*\r\njava.math.BigDecimal\r\njava.math.BigInteger\r\njava.net.*\r\njava.util.*\n```\r\n\n## Numeric handling\r\n- Literal floating point numbers (`3.1415`) are `BigDecimal`s under the hood\r\n- Principle of least surprise  \n    - [BigDecimal(double)](http://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#BigDecimal-double-)\n    - `1 + 0.1 = 1.1` (using `BigDecimal(String)` automagically)\n    - Swaps between numeric types as required (int-double)\r\n    - BEDMAS order: Brackets, Exponents, Division, Multiplication, Addition, Subtraction\r\n    - Power operator: `**`\r\n- [Numbers](http://docs.groovy-lang.org/latest/html/documentation/#_numbers)\r\n- (demo: 003\\_BigDecimal)\n\r\n## Dynamic vs. Static\n```\nx = 1.0\r\nx = new Date() //OK\r\n\r\ndef y = 1.0\r\ny = new Date() //OK\r\n\r\nint z = 1\r\nz = new Date() //Exception\n```\r\n- Tip: Use static types where possible\n- (demo: run this code snippet)\r\n\n## Scopes\r\n- Classes: like Java: class, method, block\r\n- Scripts: (not inside class)\r\n    - binding - global scope\n    - local - block scope\n- (demo: 004\\_Scopes01, 005\\_Scopes02)\n\r\nVariables are in the local scope if they have been **defined** *  \n* **defined**: static type or `def` keyword  \r\n**Methods declared in a script don't have access to the local scope**\n\n## Collections pt. I.\r\n- Native support\r\n- No need to explicitly declare Collections\r\n- `List`, `Map`, `Set`\n- [Lists](http://docs.groovy-lang.org/latest/html/documentation/#_lists)\n- [Arrays](http://docs.groovy-lang.org/latest/html/documentation/#_arrays)\n- [Maps](http://docs.groovy-lang.org/latest/html/documentation/#_maps)\n- [Working with collections](http://docs.groovy-lang.org/latest/html/documentation/#_working_with_collections)\n- [Collection literal type inference](http://docs.groovy-lang.org/latest/html/documentation/#_collection_literal_type_inference)\r\n- (demo: 006\\_Collections01 - 016\\_Collections11)\n\n## Exception handling\r\n- There is no difference between checked and unchecked exceptions\r\n- `throws` clauses are ignored\r\n\r\n## Equality\r\n- `==` is the same as `equals()` in Java\r\n- `is()` for identity check same as `==` in Java\r\n- null checking: `==` or `is()`\r\n- (demo: 017\\_Equality)\n\n# Groovy 102 - Into the Groove (Madonna)\n## Enhanced Strings\r\n- `GString` - Extension to the Java String class\r\n- For ordinary Strings apostrophes and double quotes are also valid  \r\n    `println('Hello ' + \"World!\");`\r\n- GStings must be defined with double quotes\r\n- They can contain expressions\r\n- GStrings are not Java Strings: You should not use as keys of maps or try to compare their equality\r\n- Triple quoted Strings or GStrings: Wrap a string across multiple lines  \n\n```\n\"\"\"This GString wraps\nacross two lines\"\"\"\n```\n- [Strings](http://docs.groovy-lang.org/latest/html/documentation/#all-strings)\r\n- [GStrings](http://docs.groovy-lang.org/latest/html/documentation/#_gstrings)\n- [GString and String](http://docs.groovy-lang.org/latest/html/documentation/#_gstring_and_string_hashcodes)\n- [Closures in GStrings](http://docs.groovy-lang.org/latest/html/documentation/#_closures_in_gstrings)\r\n- (demo: 018\\_GString)\n\n## GroovyBeans\r\n- Omit the explicit getters/setters but you can explicitly implement them\r\n- Auto-generated ctors: pass a map\r\n- `@Immutable`, `@Singleton` annotations\r\n- (demo: 019\\_GroovyBeans)\r\n\r\n## Closures/Function literals/Anonymous function\r\n- Special code block that is defined and then executed later\r\n- It's like a \"method pointer\"\r\n- Can be passed to methods\r\n- Can be assigned to variables\r\n- `{ [closureArguments-\u003e] statements }`\r\n- Free variables\r\n    - Variables that are not listed in the parameter list\r\n    - Local, Scope\r\n- Implicit variables\n    - `it`: you can omit the single parameter definition\n    - `this`: as in Java, the enclosing instance\n    - `owner`: this or a surrounding Closure\r\n    - `delegate`: the same as owner, but changeable\r\n- (demo: 020\\_Closures01, 021\\_Closures02, 022\\_Closures03)\n\n## Curry\r\n- A special function that takes a closure and default parameter(s)\r\n- Returns another closure that only requires the missing parameter(s)\r\n- `curry`, `rcurry`, `ncurry`\r\n\n```\r\ndef add = { a, b -\u003e a + b }\r\ndef curry = { fn, a -\u003e { b -\u003e fn(a,b) } }\r\ndef addFive = curry(add, 5)\r\nprintln addFive(3)\r\n\r\ndef add = { a, b -\u003e a + b }\r\ndef addFive = add.curry(5)\r\nprintln addFive(3)\n```\r\n\n- (demo: 023\\_Curry01, 024\\_Curry02)\n\n## Expando (Dynamic Object)\r\n- Represents a dynamically expandable bean\r\n- \"Similar\" to a Map\r\n- Doesn't have to have their properties defined in advance\r\n- It allows you to create dynamic objects via closures\r\n- Different from a map: you can call methods on the object\r\n- [Expando](http://docs.groovy-lang.org/latest/html/documentation/#_expando)\r\n- (demo: 025\\_Expando)\r\n\r\n## Collections pt. II.\r\n- Pass method to the collection\r\n- `each`, `eachWithIndex`\r\n- `collect`\r\n- `find`, `findAll`\r\n- `every`, `any`\r\n- `min`, `max`, `sum`\r\n- `join`\r\n- `inject`\r\n- `intersect`\r\n- `disjoint`\r\n- `reverse`\r\n- `removeAll`\r\n- `retainAll`\n- (demo: 026\\_Collections12 - 030\\_Collections16)\r\n- `fill`\r\n- `swap`\r\n- `frequency`\r\n- `rotate`\r\n- `permutations`\r\n- `sort`\r\n- `unique`\r\n- `subList`\r\n- `groupBy`\r\n- Set: Union, Intersection, Compliment\r\n- `asImmutable()`, `asSynchronized()`\n- (demo: 031\\_Collections17 - 037\\_Collections23)\r\n- http://groovy.codehaus.org/Collections\r\n- http://groovy.codehaus.org/JN1015-Collections\r\n- http://groovy.codehaus.org/JN1025-Arrays\r\n- http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html\r\n- http://groovy.codehaus.org/groovy-jdk/java/util/List.html\r\n- http://groovy.codehaus.org/groovy-jdk/java/util/Set.html\r\n- http://groovy.codehaus.org/groovy-jdk/java/util/Map.html\r\n- http://groovy.codehaus.org/groovy-jdk/java/lang/Object[].html\r\n\n## Ranges\r\n- List of sequential values\r\n- Extends `java.util.List`\r\n- http://groovy.codehaus.org/gapi/groovy/lang/Range.html\r\n- Inclusive range: `..`\r\n- Half-open range: `..\u003c`\r\n- `5..8`\r\n- `5..\u003c8`\r\n- `'a'..'d'`\r\n- (demo: 038\\_Ranges01 - 044\\_Ranges07)\n\n## Safe dereference operator - '?.'\r\n```\nif (person != null) {\r\n    return person.name;\r\n}\r\nelse {\r\n    return null;\r\n}\r\n\r\nperson?.name;\n```\r\n(demo: 045\\_SafeDereference01, 046\\_SafeDereference02)\r\n\r\n## Elvis operator - '?:'\n```\r\nString travelerStatus = null;\r\nstatus = (travelerStatus != null) ? travelerStatus : \"Inactive\";\r\nstatus = travelerStatus ?: \"Inactive\";\n```\n\n## Spread operator - '\\*.'\r\n- Invokes an action on all items of an aggregate object\r\n- It is equivalent to call `collect()`\n\n```\r\n(1..10).collect{it * 2}\r\n(1..10)*.multiply(2)\r\n```\n```\r\nparent*.action\r\nparent.collect{ child -\u003e child?.action }\r\nprintln ['a', 'few', 'words']*.size() //[1, 3, 5]\n```\n\n## ++ops\r\nName | Syntax | Description\n---- | ------ | -----------\nSpaceship | `\u003c=\u003e` | Compares the left and the right side: -1, 0, +1\r\nRegex | `~ =~ ==~` | Native support for Regular Expressions, see later\rField Override | `.@` | Can be used to override generated properties to provide access to a field\nSpread Field | `*.@` | Amalgamation of Spread and Field Override operations\nMethod Reference | `.\u0026` | Get a reference to a method, useful for creating closures from methods\r\nasType | `as` | Used for groovy casting, coercing one type to another\r\nMembership | `in` | Can be used as replacement for `collection.contains()`\r\nIdentity | `is` | Identity check. Since `==` is overridden in with the meaning of equality\n\n- http://groovy.codehaus.org/Operators#Operators-ArithmeticandConditionalOperators\r\n- http://www.javacodegeeks.com/2014/01/groovys-smooth-operators.html\r\n\r\n## Regular Expressions\r\n- `~` creates a Pattern from String `Pattern.compile(\".*\")`\r\n- `=~` creates a Matcher `pattern.matcher(\"aaa\")`\r\n- `==~` tests, if the String matches the pattern `\"aaa\".matches(\"a.*\")`\n- (demo: 047\\_RegEx)\n\n## Dealing with treelike data structures\r\n- XML, JSON, etc.\r\n- Builders and native language support\r\n- `XmlParser`: Supports GPath expressions for XML documents and allows updating\r\n- `XmlSlurper`: Similar to XmlParser, but applies lazy evaluation\r\n- `JsonSlurper`\r\n- `DOMCategory`: Low-level parsing of a DOM object with some syntax support\r\n- http://docs.codehaus.org/display/GROOVY/Processing+XML\n- (demo: 048\\_MarkupBuilder01 - 052\\_XmlParser02)\n\n## GPath\r\n- GPath is a path expression language\r\n- It has similar aims and scope as XPath does for XML\r\n- Dealing with nested POJOs or dealing with XML, JSON, etc.\r\n- http://groovy.codehaus.org/GPath\n- (demo: 053\\_GPath)\r\n\r\n## Memoization\r\n- Is an optimization technique\r\n- Make functions faster by trading space for time\r\n- Remembering results of method calls\n    - Returning the remembered result rather than recomputing the result again\n    - Creates a cache for the results\r\n    - Mapping between the parameters and the return value\r\n- `@Memoized`\r\n- (demo: 054\\_Memoize01, 055\\_Memoize02)\n\n# Grape\r\n- Adds dependencies to your classpath\r\n- `@Grab` http://groovy.codehaus.org/api/groovy/lang/Grab.html\r\n- http://groovy.codehaus.org/Grape\r\n- (demo: 056\\_Grape)\r\n\r\n## And so on...\r\n- IO: `URL`, `File`, `Reader`, `Writer`, `InputStream`, `OutputStream`, `Socket`, `Process`\r\n- Threads and Processes\r\n- DSL http://joesgroovyblog.blogspot.hu/2007/09/and-miles-to-go-before-i-sleep.html\r\n- SQL\r\n- `Calendar` and `Date`\r\n    http://groovy.codehaus.org/groovy-jdk/java/util/Calendar.html\r\n    http://groovy.codehaus.org/groovy-jdk/java/util/Date.html\r\n- `Object` http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html\n- (demo: 057\\_File - 065\\_Inspect)\n\n## Wait, what?! Metaprogramming\r\n- Writing of computer programs that write or manipulate other programs (or themselves)\r\n- Runtime\r\n    - Expando\r\n    - Thru Closures' delegate\r\n    - Categories (DOMBuilder, DOMCategory)\r\n    - MetaObjectProtocol (MetaClass, ExpandoMetaClass)\n- Compile Time\r\n    - AST Transformations (Abstract Syntax Tree)  \r\n    `@Immutable`, `@Singleton`, `@Memoized`, `@Synchronized`, `@Log`, `@Grab`\r\n    Project Lombok http://projectlombok.org/features/index.html\r\n- Extension Module\r\n- (demo: 066\\_MetaClass)\r\n- http://java.dzone.com/articles/introduction-groovy-runtime\n- http://www.infoq.com/presentations/groovy-metaprogramming-1\r\n- http://www.infoq.com/presentations/groovy-metaprogramming-2\n- http://groovy.codehaus.org/JN3525-MetaClasses\r\n- http://groovy.codehaus.org/ExpandoMetaClass\r\n- http://groovy.codehaus.org/Groovy+Categories\r\n- http://groovy.codehaus.org/Creating+an+extension+module\r\n- http://groovy.codehaus.org/Compile-time+Metaprogramming+-+AST+Transformations\r\n- http://www.slideshare.net/aalmiray/groovy-ast-demystified-16213614\r\n- http://glaforge.appspot.com/article/groovy-ast-transformations-tutorials\n\n# See also - Feeling Groovy (Simon and Garfunkel)\n## Interoperating\r\n- Calling Java from Groovy\r\n    - Use the classes as you would in Java\r\n    - `.jar` on the `CLASSPATH`, `import`\r\n- Calling Groovy from Java\r\n    - Put `GROOVY_HOME/embeddable/groovy-all-*.jar` into `CLASSPATH`\r\n    - `groovy.lang.GroovyShell`\r\n    - `groovy.lang.GroovyClassLoader`\r\n    - `groovy.util.Eval`\r\n    - `groovy.util.GroovyScriptEngine`\r\n    - Bean Scripting Framework (JSR-223)\r\n    - Embedded Groovy console\n\n## Interoperating - Ant\n```\r\n\u003ctaskdef name=\"groovyc\" classname=\"org.codehaus.groovy.ant.Groovyc\" classpathref=\"project.classpath\" /\u003e\r\n\u003cgroovyc\u003e\r\n    \u003cclasspath refid=\"project.classpath\" /\u003e\r\n    \u003cjavac\u003e\r\n        [...]\r\n    \u003c/javac\u003e\r\n    [...]\r\n\u003c/groovyc\u003e\n```\n\n## Interoperating - Gradle\r\n```\napply plugin: 'groovy'\n```\nhttps://docs.gradle.org/current/userguide/groovy_plugin.html\n\n## Groovy-related projects\r\n- Gradle (Build/project automation) http://www.gradle.org/\r\n- Grails (Web Application framework) http://grails.org/\r\n- GSP (Groovy Server Pages) http://groovy.codehaus.org/GSP\r\n- Griffon (Rich Application Platform - application framework for desktop apps) http://griffon.codehaus.org/\r\n- GroovyServ (Pre-invoking JVM as a server) http://kobo.github.io/groovyserv/\r\n- EasyB (BDD framework) http://easyb.org/\r\n- Gaelyk (Groovy toolkit for Google App Engine) http://gaelyk.appspot.com/\r\n- Gant (Groovy-based build system that uses Ant tasks, but no XML) http://gant.codehaus.org/\r\n- GMock (Mocking framework) http://groovy.codehaus.org/GMock\r\n- Scriptom (ActiveX/COM scripting) http://groovy.codehaus.org/COM+Scripting\r\n- Spock (Testing and specification framework) https://code.google.com/p/spock/\r\n- [...] http://groovy.codehaus.org/Related+Projects\r\n\r\n## What's next?\r\n- Groovy docs http://groovy.codehaus.org/\r\n- Groovy wiki snapshot http://docs.codehaus.org/download/attachments/63052/wiki-snapshot.pdf\r\n- DZone Refcards: Groovy http://cdn.dzone.com/sites/all/files/refcardz/rc015-groovy_online.pdf\r\n- Programming Groovy http://pragprog.com/book/vslg2/programming-groovy-2\r\n- Groovy in Action http://www.manning.com/koenig2/\r\n- Groovy Goodness Notebook https://leanpub.com/groovy-goodness-notebook/\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonatan-ivanov%2Fgroovy-training","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjonatan-ivanov%2Fgroovy-training","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonatan-ivanov%2Fgroovy-training/lists"}