Tutorial:BeanShell/5 Functions

From HandWiki


You can define define methods in BeanShell, just as they would appear in Java: <jc lang="bsh"> int addTwoNumbers( int a, int b ) {

   return a + b;

}; sum = addTwoNumbers( 5, 7 ); print(sum); </jc>

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:

<jc lang="bsh"> add( a, b ) {

   return a + b;

} foo = add(1, 2); print( foo ); 3 foo = add("Oh", " baby"); print( foo ); Oh baby </jc>

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:

<jc lang="bsh"> helloWorld() {

   print("Hello World!");

} helloWorld(); prints "Hello World!" </jc>

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.