BeanShellTutorial:5 Functions

From jWork.ORG
Revision as of 19:22, 27 December 2016 by Jworkorg (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents

Functions

You can define define methods in BeanShell, just as they would appear in Java:


int addTwoNumbers( int a, int b ) {
    return a + b;
};
sum = addTwoNumbers( 5, 7 );
print(sum);

Just as BeanShell variables may be dynamically typed, methods may have dynamic argument and return types. We could, for example, have declared our add() method above like so:


add( a, b ) {
    return a + b;
}
foo = add(1, 2);
print( foo ); '' 3
foo = add("Oh", " baby");
print( foo ); '' Oh baby

In this case, BeanShell would dynamically determine the types when the method is called and attempt to "do the right thing":

Here is another example which does not return anything:


helloWorld() { 
    print("Hello World!");
}
helloWorld(); '' prints "Hello World!"

In the first case Java performed arithmetic addition on the integers 1 and 2. (By the way, if we had passed in numbers of other types BeanShell would have performed the appropriate numeric promotion and returned the correct Java primitive type.) In the second case BeanShell performed the usual string concatenation for String types and returned a String object. This example is a bit extreme, as there are no other overloaded operators like string concatenation in Java. But it serves to emphasize that BeanShell methods can work with loose types.

Methods with unspecified return types may return any type of object (as in the previous example). Alternatively they may also simply issue a "return;" without a value, in which case the effective type of the method is "void" (no type). In either case, the return statement is optional. If the method does not perform an explicit "return" statement and the return type is not explicitly set to void, the value of the last statement or expression in the method body becomes the return value (and must adhere to any declared return typing).