The first script and groovy -e
A Groovy program is a text file whose statements run from top to bottom. There is no class to declare and no main to write. Save one line as hello.groovy and run it with the command that names the file:
hello.groovy
println 'Hello, Groovy'
groovy hello.groovy
Hello, Groovy
println is a method of the script that writes a line and a newline. The call has no parentheses and the statement has no semicolon: Groovy reads a line that ends the statement as complete. Both are optional, so the Java spelling println('Hello, Groovy'); runs too, and the course writes the short form.
The one-liner
groovy -e takes the program as an argument, which is the fastest way to try an expression:
groovy -e 'println 6 * 7'
42
The same flag reads a small program, and the shell decides where it ends:
groovy -e 'def n = 5; println n * n; println n.times { print it }'
25
01234null
A one-liner is one shell argument, so a quote inside it needs the shell's escaping, and a program longer than a line belongs in a file.
Arguments of a script
The words after the file name arrive in args, an array of strings. A script that has a default for the empty case runs with or without an argument:
greet.groovy
String name = args ? args[0] : 'reader'
println "Hello, ${name}"
groovy greet.groovy
Hello, reader
groovy greet.groovy Ada
Hello, Ada
args is a plain String[], so args.size() and the spread operator work on it. A script that needs options rather than positional words uses CliBuilder, which the command line lesson covers.
Four rules of a script
- A semicolon ends a statement, a newline does too. Two statements on one line need the semicolon; one per line needs nothing.
- Parentheses are optional in a call. println 'text' and println('text') are the same call.
- A closure is the last argument. list.each { } passes the block to each without parentheses around it.
- The file name is free. A script has no public class to match its name; the file name is only what the command types.
Related
- groovysh, the interactive shell: the same expressions without a file.
- groovyc, java -cp and Java side by side: the same program as a class file.
- Install Groovy: the command these examples need.
Автор статьи: Arthur Isaev