Packages, Imports and Scripts vs Classes
20.1 Packages and Imports
package com.example.app
import java.time.LocalDate
import java.time.format.* // star import
import static java.lang.Math.PI // static import
import static java.lang.Math.*
import java.util.concurrent.ConcurrentHashMap as CHM // import alias
import static java.lang.Math.max as maximum // static import alias
def m = new CHM()
println maximum(3, 7) + PI20.2 Scripts in Depth
A script file compiles to a class extending groovy.lang.Script. Top-level code becomes the run() method, and methods become class methods.
Binding: undeclared variables live in the binding (shared with methods). def-declared variables are local to run().
Base script classes: @BaseScript MyBaseScript base (custom DSL scripts).
Mixing classes and script code in one file is allowed. Classes inside the script become separate classes.
counter = 0 // in the binding: visible inside methods
def local = 5 // local to run(): NOT visible in methods
void bump() { counter++ } // works
bump()
println binding.variables
import groovy.transform.Field
@Field int fieldVar = 10 // promoted to a script class field
int useField() { fieldVar * 2 }20.3 Running and Organizing
groovy -cp lib/* script.groovy, #!/usr/bin/env groovy shebang, groovy -e, groovy -n -e 'println line.toUpperCase()' file.txt (line processing), groovy -p -i .bak -e 'line.replace("a","b")' file.txt (in-place edits).