Java Reference
In-Depth Information
So far, everything in a function declaration seems like a method declaration in Java.
However, there are two significant differences:
A function declaration does not have a return type
A function specifies only the names of the formal parameters, not
their types
The following is an example of a function named adder that takes two parameters
and returns a value by applying the + operator on them:
// Applies the + operator on parameters named x and y,
// and returns the result
function adder(x, y) {
return x + y;
}
Calling a function is the same as calling a method in Java. You need to use the
function name followed with the comma-separated list of arguments enclosed in
parentheses. The following snippet of code calls the adder function with two arguments
with values 5 and 10, and assigns the returned value from the function to a variable
named sum :
var sum = adder(5, 10); // Assigns 15 to sum
Consider the following snippet of code and the output:
var sum1 = adder(5, true); // Assigns 6 to sum1
var sum2 = adder(5, "10"); // Assigns "510" to sum2
print(sum1, typeof sum1);
print(sum2, typeof sum2);
6 number
510 string
This will be a surprise for you. You might have written the adder() function keeping
in mind to add two numbers. However, you were able to pass arguments of type Number,
Boolean, and String. In fact, you can pass any type of arguments to this function. This
is because Nashorn is a loosely typed language and type-checking is performed at
runtime. All values are converted to the expected types in a given context. In the first call,
adder(5, true) , the Boolean value true was converted automatically to the number 1;
in the second call, adder(5, "10") , the number 5 was converted to the String “5” and
the + operator worked as the string concatenation operator. If you want type-safety for
the parameters in functions, you will need to validate them yourself as you did inside the
factorial() function in Listing 4-2.
 
Search WWH ::




Custom Search