您的位置:首页 > 产品设计 > UI/UE

Groovy User Guide

2013-11-03 19:12 423 查看
http://groovy.codehaus.org/User+Guide

Control Structures
Logical Branching
if-else statement
Groovy supports the usual if - else syntax from Java

def x = false
def y = false

if ( !x ) {
x = true
}

assert x == true

if ( x ) {
x = false
} else {
y = true
}

assert x == y


Groovy also supports the normal Java "nested" if then else if syntax:

if ( ... ) {
...
} else if (...) {
...
} else {
...
}


ternary operator

def y = 5
def x = (y > 1) ? "worked" : "failed"
assert x == "worked"


switch statement

def x = 1.23
def result = ""

switch ( x ) {
case "foo":
result = "found foo"
// lets fall through

case "bar":
result += "bar"

case [4, 5, 6, 'inList']:
result = "list"
break

case 12..30:
result = "range"
break

case Integer:
result = "integer"
break

case Number:
result = "number"
break

default:
result = "default"
}

assert result == "number"


Looping

while {...} loops

def x = 0
def y = 5
while(y-->0){
x++
}
assert x==5


for loop

//standard java for loop
for(int i=0;i<5;i++){}
//iterate over a range
def x = 0
for(i in 0..9){
x += i
}
assert x==45
//iterate over a list
x = 0
for(i in [0,1,2,3,4]){
x+=i
}
assert x==10
//iterate over an array
array = (0..4).toArray()
x = 0
for(i in array){
x+=i
}
assert x==10
//iterate over a map
def map = ['abc':1,'def':2,'xyz':3]
x = 0
for(e in map){
x+=e.value
}
assert x==6
//iterate over values in a map
x = 0
for(v in map.values()){
x += v
}
assert x==6
//iterate over the characters in a string
def text = "abc"
def list = []
for(c in text){
list.add(c)
}
assert list == ["a","b","c"]


closures

def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
"groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];

def stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",
"We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday",
"Sa" : "Saturday" ];

stringList.each() { print " ${it}" }; println "";

stringMap.each() { key, value -> println "${key} --> ${value}" };

stringList.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };

stringMap.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };


Returning values from if-else and try-catch blocks

def method() {
if (true) 1 else 0
}
assert method() == 1

def method(bool) {
try {
if (bool) throw new Exception("foo")
1
} catch(e) {
2
} finally {
3
}
}
assert method(false) == 1
assert method(true) == 2


Operators

Arithmetic and Conditional Operators

def expression = false
assert !expression


Collection-based Operators

Spread Operator(*.)

parent*.action                             //equivalent to:
parent.collect{ child -> child?.action }


assert ['cat', 'elephant']*.size() == [3, 8]


Object-Related Operators

invokeMethod and get/setProperty (.)
Java field (.@)
The spread java field (*.@)
Method Reference (.&)
'as' - "manual coercion" - asType(t) method
Groovy == ( equals()) behavior.
"is" for identity
The instanceof operator (as in Java)


Java field(.@)

Other Operators

getAt(index) and putAt(index, value) for the subscript operator (e.g. foo[1] or foo['bar'], i.e. index is either an int or String)
Range Operator (..) - see Collections#Collections-Ranges
isCase() for the membership operator (in)


Elvis Operator(?:)

def displayName = user.name ? user.name : "Anonymous" //traditional ternary operator usage

def displayName = user.name ?: "Anonymous"  // more compact Elvis operator - does same as above


Safe Navigation Operator(?.)

def user = User.find( "admin" )           //this might be null if 'admin' does not exist
def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown


Regular Expression Operators

find (=~)
match (==~)


Table of Operators
Operator Name

Symbol

Description

Spaceship

<=>

Useful in comparisons, returns -1 if left is smaller 0 if == to right or 1 if greater than the right

Regex find

=~

Find with a regular expresion? See Regular Expressions

Regex match

==~

Get a match via a regex? See Regular Expressions

Java Field Override

.@

Can be used to override generated properties to provide access to a field

Spread

*.

Used to invoke an action on all items of an aggregate object

Spread Java Field

*.@

Amalgamation of the above two

Method Reference

.&

Get a reference to a method, can be useful for creating closures from methods

asType Operator

as

Used for groovy casting, coercing one type to another.

Membership Operator

in

Can be used as replacement for collection.contains()

Identity Operator

is

Identity check. Since == is overridden in Groovy with the meaning of equality we need some fallback to check for object identity.

Safe Navigation

?.

returns nulls instead of throwing NullPointerExceptions

Elvis Operator

?:

Shorter ternary operator

Bitwise Operations
Operator Symbol

Meaning

<<

Bitwise Left Shift Operator

>>

Bitwise Right Shift Operator

>>>

Bitwise Unsigned Right Shift Operator

|

Bitwise Or Operator

&

Bitwise And Operator

^

Bitwise Xor Operator

~

Bitwise Negation Operator

<<=

Bitwise Left Shift Assign Operator

>>=

Bitwise Right Shift Assign Operator

>>>=

Bitwise Unsigned Right Shift Assign Operator

|=

Bitwise Or Assign Operator

&=

Bitwise And Assign Operator

^=

Bitwise Xor Operator

Scripts and Classes

Statements

Reserved Words

Strings and GString

http://groovy.codehaus.org/User+Guide
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: