1 defining closures using lambdas and closures 1.1
A closure is a block of code that replaces a method or class.
Closures in groovy are based on the structure behind: {list of parameters-> closure body}
. Where the ->
previous value is the declared closure parameter.
If there is only one variable, you can use the intrinsic variable it
.
If no return value is defined, the ->
value behind is returned. it
the use of the return value, see the following example,
package closures class Closurestest { Static main (args) { //return input, using intrinsic variable it def Returninput = {it}; assert "test" = = Returninput ("test"); //return input, do not use intrinsic variable it def returnInput2 = {S->s}; assert "test" = = ReturnInput2 ("test"); }   |
1.2 Defining default values in closures
Closures, you can also define default values for parameters.
package closures , class Closuresdefaultvalue { static Main (args) { def multiply = { int a,< Strong>int b=10-> A * b; }; assert multiply (2) = =; assert multiply (2,5) = = Ten } &NBSP; |
1.3 Example: Using closures in each method
Example of using closures in a collection,
Package Closures class Closureseach { Static Main (args) { list<integer> list = [5,6,7,8]; println ("= = = Custom Variable"); List. each {line-- print line+ ","; }; println ("\r\n==== intrinsic variable"); List. each ({ print it+ ","; }); println ("\r\n==== calculated from 1 to 10 and"); def total = 0; (1..10). each { Total + = it; }; println Total; } } |
1.4 Example: Sort a list by the length of a string
Package Closures class Closuressort { Static Main (args) { def List strings = "This is a long sentence". Split (); Strings.sort{s1,s2 S1. size () <=> S2. size (); }; println strings; } } |
Output
[A, is, this, long, sentence] |
1.5 using the With method
Each groovy object has a with
method in which multiple methods or properties are allowed to be called, and the values that are set or the methods that are executed are applied to the object.
package closures , import java.util.List; &NBSP; class withobj { String property1; String Property2; list<string> List = []; def addelement (value) { list << value; }; def returnproperties () { "Property 1: $property 1,property 2: $property 2"; } |
Package Closures class Closureswithmethod { Static Main (args) { def sample = new withobj (); def result = Sample. with { property1= "Input 1"; Property2= "This is cool"; addelement ("Ubuntu"); addelement ("Android"); addelement ("Linux"); returnproperties (); }; println result; assert 3==sample.list.size (); assert "Input 1" = = Sample.property1; assert "This is cool" = = Sample.property2; assert "Linux" = = sample.list[2]; def sb = new StringBuilder (); SB. with { Append ("this"); Append ("is"); Append ("appended"); }; println sb; } } |
Output:
Property 1:input 1,property 2:this is cool This is appended |
15 using Lambdas and closures