Groovy User Guide (2)

xiaoxiao2021-03-06  52

2, closing bag

(1 Overview

l Closure is a powerful method for transmitting executing code blocks.

l You can view the closure as anonymous in Java, but only a single (anonymous) method.

l Hethers can be used as an alternative to circulation

[1, 2, 3, 4]. Each {Println (IT)}

l Use closures to make exception handling and closing resources easier, for example, please see Groovy SQL

(2) Compare closure and anonymous inside categories

l Different from Java anonymous inside, Groovy supports "True Closure": The status can be passed to the outside of the closure

l Partial variables can be used and modified when closing, and any variable created in the closure can be used as partial variables, visible to the outside.

l Look at the example below:

COUNT = 0

Last = 0

[1, 2, 3, 4] .each {count = it; las = it}

Println ("The Sum IS $ {Count} and the last item was $ {last}")

Output Result: The Sum is 10 and the last item was 4

(3) Closed bag is a normal object

l Closure is the object that is passed and called when needed.

l can therefore be used as it is as follows:

C = {Println ("Hello $ {IT}")}

C.call ('James')

c.call ('bob ")

l Closets are compiled into new classes for expanding the Groovy.lang.Closure class.

l The following omitted Writings is equivalent.

C = {Println ("Hello $ {IT}")}

C ('James')

C ('bob')

(4) Parameters of closed bags

l Closure can have any number of parameters

l Default, closed bag has a single default parameter: "IT"

l You can specify a list of parameters in the beginning of the closure statement.

C = {A, B, C | Println ("Hello $ {a} $ {b} $ {c}")}

C ('Cheese', 234, 'Gromit')

l The following is another useful example of using two parameters, and it has been told in "Groovy Quick Start":

Value = [1, 2, 3] .inject ('counting:') {STR, ITEM | STR ITEM}

askERT VALUE == "Counting: 123"

Value = [1, 2, 3] .INJECT (0) {count, item | count item}

askERT VALUE == 6

转载请注明原文地址:https://www.9cbs.com/read-115192.html

New Post(0)