Learn how to use groovy (chapter 2 of the Translation: closure)

Source: Internet
Author: User

Chapter 2: Closure

Informal wizard

When using Java programming, manyCodeModifier: either a static method (class method) or an instance method. (The code can also add constructors, initial values, and initial expressions, but these are not important here ). A method that encapsulates the code in the braces and assigns this code a method name. All these methods must be defined in a class of a certain type. For example, if you want to write a method, return an integer Square, as shown below:

Package example. Math;

Public class mymath {
Public static long square (INT numbertosquare ){
Return numbertosquare * numbertosquare;
}
}
To use this square () method, you need to reference this class and method by name as follows:
Import example. Math. mymath;

...

Int X, Y;
X = 2;
Y = example. Math. mymath. Square (X );

// Y will equal 4. in groovy, you can also do this, but you can also define this code before declaring classes and methods. This is called closure (closure ), A closure is one or more ofProgramThe main difference between a statement, a closure, and a method is that a closure does not require a class or method name. The following shows the square () method written as a closure:
Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

{Numbertosquare->
Numbertosquare * numbertosquare
};

At this time, you can see that the executable code is the same except that you do not need to declare a class or assign a method name for a piece of code. As you can see in the annotations, the above example is not so useful because once it is created, there is no way to use the closure. It does not have an identifier (method name). How can we call it? To do this, you can assign a variable to the closure when it is created. Then, you can use the variable as the identifier of the closure for calling, as shown below:
Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

// Initiate Variables

Int X, Y;
X = 2;

// Create closure and assign it to variable C

Def c = {numbertosquare-> numbertosquare * numbertosquare}

// Using C as the identifer for the closure, make a call on that closure
Y = C. Call (X );

// Y will equal 4;

The advantage of a closure is that you can create a closure, assign it a variable, and pass it in any other variable. At the beginning, you don't think there is anything, but when you have a deep understanding of groovy, you will find that closures are useful everywhere.

For example, expand Java in groovy. lang. vector class, we add a simple method that allows you to apply a closure to all elements in the vector, a new class: gvector, as follows:

Package example;

Public class gvector extends java. Lang. Vector {

Public gvector (){
Super ();
}

Public void apply (c ){
For (INT I = 0; I <this. Size (); I ++ ){

Old_element = This. elementat (I );
New_element = C. Call (old_element );
This. Set (I, new_element );

}
}
}

The apply () method carries a closure as the input parameter. Each element in the gvector is called in the element for transmission, the value returned as a result is then used to replace this element, so that you can use the closure with a certain element to modify the content in gvector when appropriate, and can be converted into other things.

Now, we can call this new apply () method with any closure we think of. For example, we will create a new gvector with some elements, the square we created previously is passed in the closure.

Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

Example. gvector gvect = new example. gvector ();
Gvect. Add (2 );
Gvect. Add (3 );
Gvect. Add (4 );

C = {numbertosquare-> numbertosquare * numbertosquare ;}

Gvect. Apply (C );

// The elements in the gvector have all been squared.

Because the apply () method in gvector can be used with any closure, you can use any closure. Let's take a look at the example below. It uses a closure to print the messages it passes.

Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

Example. gvector gvect = new example. gvector ();
Gvect. Add (2 );
Gvect. Add (3 );
Gvect. Add (4 );

C2 = {value-> println (value );}

Gvect. Apply (C2 );

// The elements in the gvector have all been printed.

If you run the above script and assume that you define and compile the gvector class, the input will be as follows:

C:/> groovy myscript. Groovy
4
9
16
C:/>

In addition to a closure variable, you can also directly declare it as a parameter in the method. The code above can be rewritten to the following form:

Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

Example. gvector gvect = new example. gvector ();
Gvect. Add (2 );
Gvect. Add (3 );
Gvect. Add (4 );

Gvect. Apply {value-> println (value );}

// The elements in the gvector have all been printed.

The result of this example is the same as that of the first one, but the closure is directly defined as a parameter and applied to the apply method in gvector.

Closure and code block (closures vs. code blocks)

Closures are similar to rules of Java or groovy code blocks, but they are actually different. The code in the code block of the rule (whether it is a method block, a class block, a synchronization block, or only a block of Code) will be executed once the Virtual Machine encounters it. For the closure, the statement segments in the braces are not executed until the call () method in the closure is called. In the previous example, the closure statement is declared in the same row but not executed at that time. It is executed only when the call () method is explicitly called. This is a very important difference between closures and code blocks! They seem to be similar, but in fact they are not. Once the Java and groovy blocks of the rule are met, the closure is not like this. It is executed only when called by the call () method.

Official wizard

In groovy, a closure is an anonymous code. It can contain parameters (multiple parameters), return a value, and reference it, you can use the variables defined in the corresponding range. in many ways, it is similar to the internal class in Java. in terms of usage, closures in groovy are similar to Java developers using anonymous internal classes. However, closures in groovy are more powerful than anonymous internal classes, it is more convenient to specify and use.

Syntax for defining closures

The syntax defined by the closure is as follows:

Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL
{[Closurearguments->] Statements}
[Closurearguments->] is an optional parameter list separated by commas (,). Statements may not exist and may contain multiple groovy statement blocks.
The parameter list is similar to the parameter list in the method, and can be of type or no type. when a parameter table is specified, the "->" character is required to separate the closure bodies. The "statements" part consists of 0, 1, or multiple groovy statements.
The correct closure definition is as follows:
Unable to find source-code Formatter for language: groovy. Available versions are: XHTML, JavaScript, Java, none, HTML, actionscript, XML, SQL

{Item ++}

{Println it}

{++ It}

{Name-> println name}

{String X, int y-> println "Hey $ X the value is $ Y "}

{Reader->
While (true ){
Line = reader. Readline ()
}

--- "To be continued ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.