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
Authors have earned$9,893,383writing, 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
The Leanpub 45-day 100% Happiness Guarantee
Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
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
C++ Best Practices
Jason TurnerLevel up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
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.
Functional Design and Architecture
Alexander GraninSoftware Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
Atomic Kotlin
Bruce Eckel and Svetlana IsakovaFor both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
C++20
Rainer GrimmC++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
The book is almost daily updated. These incremental updates ease my interaction with the proofreaders.
Introductory Statistics with Randomization and Simulation
Mine Cetinkaya-Rundel, Christopher Barr, OpenIntro, and David DiezA complete foundation for Statistics, also serving as a foundation for Data Science, that introduces inference using randomization and simulation while covering traditional methods.
Leanpub revenue supports OpenIntro, so we can provide free desk copies to teachers interested in using our books in the classroom.
More resources: openintro.org.
Java OOP Done Right
Alan MellorObject Oriented Programming is still a great way to create clean, maintainable code. But only if you use it right.
This book gives you 25 years of OO best practice, ready to use.
You'll learn to design objects behaviour-first, use TDD to help, then confidently apply Design Patterns, SOLID principles and Refactoring to make clean, crafted code.
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.
Composing Software
Eric ElliottAll software design is composition: the act of breaking complex problems down into smaller problems and composing those solutions. Most developers have a limited understanding of compositional techniques. It's time for that to change.
Cloud Strategy
Gregor Hohpe“Strategy is the difference between making a wish and making it come true.” A successful migration to the cloud shouldn’t be driven by wishes, but guided by a sound strategy, frameworks, and decision models. This book tells you how—without becoming superficial nor getting lost in technology and product details.
Top Bundles
- #1
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
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... - #3
Cisco CCNA 200-301 Complet
4 Books
Ce lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301. - #4
CCDE Practical Studies (All labs)
3 Books
CCDE lab - #5
Modern Management Made Easy
3 Books
Read all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization. - #6
The Future of Digital Health
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 and how technology giants such as Amazon or Google want to conquer... - #7
Modern C++ by Nicolai Josuttis
2 Books
- #8
Django for Beginners/APIs/Professionals
3 Books
- #9
"The C++ Standard Library" and "Concurrency with Modern C++"
2 Books
Get my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library... - #10
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité...