Java Reference
In-Depth Information
curly brackets {} in a double quoted string of text. The following JavaScript resides in
a file named recipe18_3.js , and it can be executed by the jjs tool as a shell
script. The string interpolation works in this example because the script has been made
executable by adding the shebang as the first line. Refer to Recipe 18-10 for more in-
formation on the shebang.
#! /usr/bin/env
function gallons(width, length, avgDepth){var volume
= avgDepth * width * length;
return volume
* 7.48; }
print("Gallons of water in pool: ${gallons(16,32,5)}");
Execute the JavaScript file via jjs as follows:
jjs src/org/java8recipes/chapter18/js/recipe18_3.js
Gallons of water in pool: 19148.800000000003
Note This example JavaScript file cannot be run from a ScriptEngineManager be-
cause it contains a shebang (it is an executable script).
How It Works
When you're using Nashorn's shell scripting features, you can embed expressions or
values in double-quoted strings of text by enclosing them in dollar signs and curly
braces ${...} . This concept is known a string interpolation in the Unix world, and
Nashorn borrows the concept to make it easy to develop shell scripts for evaluating and
displaying information. String interpolation makes it possible alter the contents of a
string, replacing variables and expressions with values. Using this feature, it is easy to
embed the contents of a variable in-line within a string without performing manual
concatenation.
In the example for this recipe, a script that is stored within a .js file contains an
embedded expression, and it calls on a JavaScript function to return the calculated
number of liquid gallons. This is likely the most useful technique for real-world scen-
arios, but it is also possible to make use of embedded expressions when using the jjs
tool as an interactive interpreter.
Search WWH ::




Custom Search