Groovy offers a Java-based form of procedure abstraction. The language offers both functions and sequencing aspects to allow a programmer to manage procedures and control flow.
For both methods and functions, Groovy supports both function procedure and proper procedure definitions. Proper procedures are defined by defining a return type of void and function procedures are defined with a return type of an object or primitive.
Object values are passed by reference, meaning the reference value, like a pointer in C, is passed in by copy. The result is an object accessed in a method is the same object from the calling method.
Java does not support passing functions as variables, so Groovy added an operator, the & operator, to represent the equivalent to a function pointer.
Functions and Methods
Any Java class, and by extension any Groovy class, offers the ability to have methods exposed. These methods can encapsulate a set of operations, making them reusable. Also, since they are attached to a class, they can act upon encapsulated data as described in Data Abstraction and Type Systems.class AnotherExample { private int index; private String name; // Remember, Groovy is public by default String toString() { return name + ":" + index; } }In addition to class-based methods, Groovy also offers a type of standalone function. This function can also encapsulate a set of operations and be reused. The function is not bound to a class, but instead is bound to the script itself, creating a form of JavaScript-like closure. The function can be bound to a variable and passed into a function for the purposes of callbacks or other instances where a dynamic function needs to be provided to a method.
def callback(def value) { println(value) } def needsCallback(Closure c) { c(“do something”) } // Note the use of this to reference the callback // in the script context needsCallback(this.&callback)Note: in Groovy a stand-alone function is called a closure.
For both methods and functions, Groovy supports both function procedure and proper procedure definitions. Proper procedures are defined by defining a return type of void and function procedures are defined with a return type of an object or primitive.
class Example { void properProcedure(int param1, String param2) { // do something } int functionalProcedure(int param1, String param2) { // do something and return a value return 0; } }
Parameters and Arguments
When passing parameters into a Groovy method or function, all values are in only and passed by copy. This means that primitive values are copied into the function for use.Object values are passed by reference, meaning the reference value, like a pointer in C, is passed in by copy. The result is an object accessed in a method is the same object from the calling method.
Java does not support passing functions as variables, so Groovy added an operator, the & operator, to represent the equivalent to a function pointer.
No comments:
Post a Comment