Truthiness, imports and comments
Three small rules shape every Groovy script: a condition accepts any object and decides for itself what false means, the compiler writes the common imports for you, and a comment is a line the compiler drops.
What is false
False is: false, null, the number zero, an empty string, an empty collection and an empty map. Everything else is true, including the string '0' and a list with one null in it:
truth.groovy
def emptyText = ''
def zero = 0
def emptyList = []
def oneItem = [null]
def word = '0'
println emptyText ? 'true' : 'false'
println zero ? 'true' : 'false'
println emptyList ? 'true' : 'false'
println oneItem ? 'true' : 'false'
println word ? 'true' : 'false'
groovy truth.groovy
false
false
false
true
true
The rule is asBoolean(), a method every class may declare. A class of your own that should be false when empty implements it, and every if in the program agrees.
The imports Groovy writes
A Groovy file starts with these packages already imported: java.lang, java.util, java.io, java.net, groovy.lang, groovy.util, and the classes java.math.BigDecimal and java.math.BigInteger. The script below uses four of them with no import line:
imports.groovy
List<String> names = new ArrayList<>()
names.add('Ada')
Map<String, Integer> ages = new HashMap<>()
ages.put('Ada', 36)
File file = new File('data.txt')
BigDecimal price = 9.99
println names.size()
println ages['Ada']
println file.name
println price * 2
groovy imports.groovy
1
36
data.txt
19.98
A class outside those packages needs its import, and an import is one line at the top: import java.time.LocalDate. A static method of a class is imported with import static java.lang.Math.max.
Comments
comments.groovy
#!/usr/bin/env groovy
// A line comment runs to the end of the line.
/*
* A block comment spans lines.
* The compiler drops both forms.
*/
/** A Groovydoc comment documents what follows. */
String greet(String name) {
"Hello, ${name}" // a trailing comment is still a comment
}
println greet('Ada') // prints one line
groovy comments.groovy
Hello, Ada
The first line is a shebang: on a Unix system it lets ./comments.groovy run the file directly, with groovy from the PATH. The double-star form is Groovydoc, which groovydoc turns into HTML documentation.
Related
- if, else and the ternary: the conditions this lesson feeds.
- Operators: the Elvis operator, which is truthiness in one character.
Article author: Arthur Isaev