11, statement
(1) Section
l Groovy uses a syntax similar to Java, but the semicolon of the statement is optional.
l If a statement is one statement, you can omit the semicolon; if there are multiple statements on a line, you must use a semicolon to separate
X = [1, 2, 3]
Println X
Y = 5; x = y 7
Println X
askERT X == 12
l A statement can span multiple lines, for the parameter list or complex expression of the method, it may do this
X = [1, 2, 3,
4, 5, 6]
PRINTLN
x
)
IF (x! = null&&
x.size ()> 5) {
Println ("Works!")
} else {
Assert False: "Should Never Happen $ {x}"
}
(2) method call
l The syntax and Java called by the L method, support static and instance methods
Class foo {
Calculateprice () {
1.23
}
Static void main (args) {
Foo = new foo ()
P = foo.calculateprice ()
askERT P> 0
Println "Found Price:" P
}
}
Note, return keywords are ultimately optional in the method; the same, the return type is also optional (the default is Object)
l The call to the method in the middle of Groovy can omit parentheses, as long as there is parameters, and no ambiguity
(3) Pass the naming parameters
l When the method is called, you can pass the named parameter, the name of the parameter and the value divided (like the MAP syntax), and the parameter name is unique identifier string.
Bean = new expando (name: "James", Location: "London", ID: 123)
Println "Hey" bean.name
askERT bean.id == 123
l The current method is transmitted to implement only MAP-based calls or JavaBean constructors.
(4) Transfer closure to method
Please refer to "GROOVY Quick Getting Started"
(5) Dynamic method assignment
l If the variable does not use type to force, dynamic method assignments are used, which is often referred to as dynamic types, while Java defaults static types.
l You can mix dynamic and static types in your code.
DynamicObject = "Hello World" .ReplaceAll ("World", "Gromit")
DynamicObject = "!"
askERT DYNAMICOBJECT == "Hello Gromit!"
String staticObject = "Hello there"
StaticObject = "!"
askSERT staticObject == "Hello there!"
(6) attribute
l Access attribute through ". attribute name"
Bean = new expando (Name: "James", Location: "London", ID: 123) Name = bean.name
Println ("Hey $ {Name}")
Bean.location = "vegas"
Println bean.name "is now in" bean.location
askERT bean.location == "vegas"
l The special bean expando above is running, dynamically adding properties
l It is actually a behavior like dynamic bean map: increasing the Name / Value pair and equivalent Getter / setter method, just as a real bean
(7) Safety navigation
l If you are accessing complex objects, you don't want to meet NullPointerexception exceptions, you can use "->" instead of "."
Foo = NULL
Bar = foo-> Something-> mymethod ()
askBAR == NULL