The Groovy 2 Tutorial
The Groovy 2 Tutorial
An introductory text for Groovy developers
About the Book
The Groovy 2 Tutorial takes you through the essential aspects of the Groovy programming language. You'll learn about the general syntax and pick up helpful tips. Importantly, you'll see where Groovy can make programming more about solving problems and less about tedious syntax.
Groovy is a great programming language for those who enjoy programming (or are new to it!) but find languages such as Java to be cumbersome. Learning Groovy will give you the ability to not only write Groovy programs but to also unlock a range of great technologies such as Grails and Gradle as well as frameworks that run on the Java Virtual Machine such as Spring.
Written in a straight-forward tone, each chapter focusses on a specfic language element and provides a range of examples for you to try out in the Groovy Console. You don't need lots of tooling - just some time and a basic PC or laptop.
Table of Contents
-
-
Introduction
- Something Wrong?
- Bookmarks
- Conventions Used in This Book
- Your Rights and This Book
- Legal Notices
-
Introduction
-
I Getting started
- 1. Introduction
-
2. Installing Groovy
- Don’t Install Groovy
- Install a Java Virtual Machine
- Install Groovy
-
3. Your first lines of Groovy
- Examining the script
- 4. Running a script
- 5. Compiling Groovy
-
6. Comments
- Single-line comments
- Multi-line comments
- Usage to avoid
- Groovydoc
-
7. Statements
- Usage to avoid
-
8. The
assert
statement- Handling failed assertions
- 9. Reserved Words
-
10. Packages
-
Using
import
- Built in Libraries
- Useful third-party libraries
-
Using
- 11. Grape
-
II Variables
- 12. Introduction
-
13. Declaring Variables
- Variable names
- Data Types
-
14. Objects
- Declaring and using a class
- Useful Methods
- Existing classes
- Classes and literal values
-
15. Booleans
- Useful Methods
-
16. Numbers
- Integers
- Decimals
- Scientific notation
- Number Systems
- Useful Methods and Properties
-
17. Strings
- Escape sequences
- GStrings
- Multiline Strings
- Building Strings
- Useful Methods
-
18. Collections
- Lists
- Maps
-
19. Arrays
- Manipulating arrays
-
20. Ranges
- Half-Open Ranges
- Ranges of Objects
- Ranges and List Indexes
- Ranges and Loops
- Useful Methods
-
21. Regular Expressions
- Regular Expression Syntax
- Useful Methods
-
22. Data types
- Groovy’s use of types
- Using a specific type
-
The
null
Value - Available data types
- Type Conversions
-
III Operators
-
23. Introduction
- Arithmetic and Conditional Operators
- String Operators
- Regular Expression Operators
- Collection Operators
- Object Operators
- 24. Operator Overloading
-
25. Numeric Operators
- Operator Precedence
- Order of Precedence
- 26. Simple Assignment Operator
- 27. The Complement Operator
-
28. Equality Operators
- What Is Equality?
- Precedence
- Overloading Equality
-
29. Arithmetic operators
- Additive Operators
- Multiplicative Operators
- The Power operator
- Precedence
-
30. Relational Operators
- Spaceship
- Overloading the relational operators
-
31. Increment and Decrement Operators
- Overloading the Increment and Decrement Operators
-
32. Conditional Operators
- What Is Truth?
- Evaluation
- Conditional-And
- Conditional-Or
- Conditional Operator
-
33. Bitwise Operators
- Truth Tables
- Flag example
- Shift Example
- 34. Compound Assignment Operators
-
35. String Operators
- Concatenate Operator
- Append Operator
- Remove Operator
- Remove In-Place Operator
- Repeat Operator
- Repeat In-PlaceOperator
- Increment and Decrement Operators
- Warning: Strings Are Expensive!
- Templates
-
36. Regular Expression Operators
-
Find (
=~
) -
Match (
==~
)
-
Find (
-
37. Collection operators
- Membership Operator (Lists and Maps)
- Append (Lists and Maps)
- Addition (Lists and Maps)
- Subtraction (Lists and Maps)
- Compound Assignment Operators (Lists and Maps)
- Spread Operator (Lists)
- Spread-Dot Operator (Lists)
- A Little Set Theory
-
38. Object Operators
- Safe Navigation Operator
- Casting Operator
- Identity Operator
- Type Comparison
- Field Operator and Method Reference
-
23. Introduction
-
IV Control Flow Statements
- 39. Introduction
-
40. Blocks
- Variable Scope
-
41. The
if
Statement-
if
-else
-
if
-else if
-else
-
-
42. The
switch
Statement-
The Versatile Groovy
switch
- Using Ranges
- Using Regular Expressions
- Using Class Checks
-
The Versatile Groovy
-
43. The
for
Loop-
The
for-in
Loop - The Java for-each
-
A C-style
for
Loop
-
The
-
44. The
while
loop-
There is no
do...while
loop
-
There is no
-
45. Branching statements
- break
- continue
- Labelled branching
- return
-
V Exceptions
- 46. Introduction
-
47. Common Exceptions
- java.lang.NullPointerException
- java.lang.AssertionError
- java.lang.NumberFormatException
- groovy.lang.MissingPropertyException
- groovy.lang.MissingMethodException
- java.lang.IndexOutOfBoundsException
- java.lang.ArrayIndexOutOfBoundsException
- 48. Anatomy of an Exception
-
49. Try-Catch-Finally
- Scope
- try-catch
- try-catch-finally
- try-finally
- 50. How Much Should We try?
-
51. Causing an Exception
- Constructing an Exception
- Creating Your Own Exception
- 52. Catching Errors
- 53. Methods and Exceptions
-
VI Methods
- 54. Introduction
- 55. The Basics
-
56. Parameters
- Declaring data types for parameters
- Multiple parameters
- 57. Default Values for Parameters
- 58. Named Arguments
- 59. Variable Arguments (Varargs)
-
60. Return value
- Multiple Returns
- Declaring data types for return values
- Sequential method calls
- 61. Throwing an exception
- 62. Documenting a method
-
63. Techniques
- Valid parameters
- Comment your method
- Check the parameters
- Get really typed
- Testing
-
VII Closures
- 64. Introduction
-
65. Introducing Closures
- Anonymous Functions
- The ‘it’ parameter
- 66. Parameters
- 67. Returning Values
-
68. Closures as Method Parameters
- Methods with Closure Parameters
-
69. Loops and closures
-
each
-
collect
-
sort
-
-
70. Useful Methods That Use Closures
-
any
-
find
andfindAll
-
split
-
with
-
-
71. Closure scope
- A More Involved Example
-
VIII Object-oriented programming
- 72. Introduction
-
73. Expando
- Using Expando with CSV data
-
74. The basics of OO
- Classes
- Interfaces
- Inheritance
- Traits
- Packages
- Summary
-
75. Properties and Fields
- Properties
- Fields
- Default values
- Casting maps to objects
-
76. Getters and Setters
- Fields
- Pseudo properties
-
77. Methods
- Overloading
-
78. Constructors
- Writing your own constructor(s)
- TupleConstructor annotation
- Instance initializer blocks
- When and How Things Happen
- Constructors and instance methods
-
79. Class Methods and Variables
- Static initializer blocks
-
80. Final Variables
- Final fields and the map-like constructor
- Final objects
- Final classes and methods
-
81. Access Modifiers
- Applying Access Modifiers
-
82. Useful Annotations
- ToString
- EqualsAndHashCode
- Canonical
- Immutable
- 83. Let Go of That Instance!
- 84. Enums
-
85. The
synchronized
modifier
-
IX More object-oriented programming
-
86. Introduction
- The Shapes demo
-
87. Organising your code
- Packages
- Compiling and running
- 88. Naming your packages
- 89. Packages and directory structure
- 90. The Shapes demo - packages
- 91. Interfaces
- 92. Referring to objects by their interface
-
93. General advice for interfaces
- Groovy interfaces don’t allow default methods
- The constant interface antipattern
- 94. The Shapes demo - Interfaces
- 95. Traits
- 96. Trait properties and fields
- 97. Trait methods
- 98. Trait static members
-
99. The class-trait relationship
- Self types
- 100. Traits and interfaces
- 101. Implementing multiple traits
- 102. The Shapes demo - Traits
-
103. Inheritance
- Some inheritance theory
-
104. Subclassing
- Type comparison
- 105. Final Classes and Methods
- 106. Abstract classes
- 107. The Shapes demo - Inheritance
-
86. Introduction
-
X Going further
-
108. Other Topics
- Type Checking
- Static Compilation
- Metaprogramming
- Generics
- Inner Classes
- Single abstract methods
-
109. The great beyond
- Build large applications
- Use the Groovy ecosystem
-
Appendix: The Shapes demo code listing
-
package org.groovy_tutorial.shapes
-
package org.groovy_tutorial.shapes.triangle
-
package org.groovy_tutorial.shapes.triangle
-
- Colophon
-
108. Other Topics
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
Do Well. Do Good.
Authors have earned$11,714,583writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
Recipes for Decoupling
Matthias NobackWrite software that survives
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
CQRS by Example
Carlos Buenosvinos, Christian Soronellas, and Keyvan Akbary- Leverage your Software Architecture skills by learning everything about CQRS in detail with lots of examples
- Develop faster applications by applying CQRS and fostering Read Models and Projections
- Learn how to apply CQRS into a brownfield project from a pragmatic approach
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Maîtriser Apache JMeter
Philippe Mouawad, Bruno Demion (Milamber), and Antonio Gomes RodriguesToute la puissance d'Apache JMeter expliquée par ses commiteurs et utilisateurs experts. De l'intégration continue en passant par le Cloud, vous découvrirez comment intégrer JMeter à vos processus "Agile" et Devops.
If you're looking for the newer english version of this book, go to Master JMeter : From load testing to DevOps
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
The PowerShell Scripting and Toolmaking Book
Don Jones and Jeff HicksLearn the patterns, practices, and details of PowerShell Scripting and Toolmaking from the industry's two most recognized experts on the subject.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
Introduction to Data Science
Rafael A IrizarryThe demand for skilled data science practitioners in industry, academia, and government is rapidly growing. This book introduces concepts from probability, statistical inference, linear regression and machine learning and R programming skills. Throughout the book we demonstrate how these can help you tackle real-world data analysis challenges.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #6
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon...