Java Reference
In-Depth Information
if (employee == null) {
loc = null;
} else {
Department dept = employee.getDepartment();
if (dept == null) {
loc = null;
} else {
loc = dept.getLocation();
}
}
That's quite an expansion just to check for nulls. Here's the Groovy version:
Location loc = employee?.department?.location
The safe de-reference operator returns null if the reference is null. Otherwise it proceeds
to access the property. It's a small thing, but the savings in lines of code is nontrivial.
Continuing on the theme of simplifying code over the Java version, consider input/output
streams. Groovy introduces several methods in the Groovy JDK that help Groovy simplify
Java code when dealing with files and directories.
B.7. File I/O
File I/O in Groovy isn't fundamentally different from the Java approach. Groovy adds sev-
eral convenience methods and handles issues like closing your files for you. A few short
examples should suffice to give you a sense of what's possible.
First, Groovy adds a getText method to File , which means that by asking for the text
property you can retrieve all the data out of a file at once in the form of a string:
String data = new File('data.txt'). text
Accessing the text property invokes the getText method, as usual, and returns all the
text in the file. Alternatively, you can retrieve all the lines in the file and store them in a list
using the readLines method:
List<String> lines = new File(" data.txt" ). readLines ()*.trim()
Search WWH ::




Custom Search