Comments and Style
Prerequisites: Methods
Comments
#!/usr/bin/env groovy
// A single-line comment
def taxRate = 0.2 // after code
/*
* A block comment
* spanning several lines
*/
/**
* Returns the price including tax.
* @param price the net price
* @return the gross price
*/
def withTax(price, rate) {
price * (1 + rate)
}
println withTax(100, taxRate)
120.0
//and/* ... */work as in Java./** ... */comments are Groovydoc, turned into HTML documentation by thegroovydoctool and shown by your IDE.- A shebang line (
#!/usr/bin/env groovy) is allowed as the very first line, so a script can be run directly on Linux and macOS afterchmod +x.
Idiomatic Groovy style
The official style guide (on groovy-lang.org) boils down to: write less ceremony than Java.
- Leave out semicolons, and
public(it's the default). - Use
deffor local variables when the type is obvious; use types for method signatures and public APIs. - Use single quotes for plain strings, double quotes only when interpolating.
- Use
==for equality,?.and?:for nulls, and Groovy Truth (if (list)) instead of explicit checks. - Omit
returnon the last line of short methods and closures. - Use list/map literals and collection methods (
collect,findAll) instead of manual loops. - Indent with four spaces;
camelCasenames;PascalCaseclasses. - Keep parentheses when leaving them out would hurt readability —
println foo(bar)is fine,println foo baris not.
Tools
- CodeNarc — a static analysis tool with hundreds of rules for Groovy style, bugs, and complexity; it has Gradle and Maven plugins.
- IntelliJ IDEA — reformats Groovy code and flags common problems.
- npm-groovy-lint — CodeNarc packaged as a command-line tool, handy for linting and formatting Jenkinsfiles.
What's next
You now know the core of Groovy. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with closures in depth.