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
Groovy also supports the normal Java "nested" if then else if syntax:
ternary operator
switch statement
Looping
Returning values from if-else and try-catch blocks
Operators
Arithmetic and Conditional Operators
Collection-based Operators
Spread Operator(*.)
Object-Related Operators
Java field(.@)
Other Operators
Elvis Operator(?:)
Safe Navigation Operator(?.)
Regular Expression Operators
Table of Operators
Bitwise Operations
Statements
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 |
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相关文章推荐
- GradleUserGuide中文版 7)Java构建 8)依赖管理基础 9)Groovy入门
- NVIDIA PhysX SDK 3.3.4 Documentation User's Guide翻译 --Vehicles
- Hyperledger Fabric CA User’s Guide——配置设置(四)
- DVI-to-RGB(Sink)IP User Guide
- VCS and DVE user guide
- sqoop 中文文档 User guide 三 export
- Apache Jakarta Project: commons FileUpload User Guide[翻译]
- MongoEngine 中文文档 系列教程 User Guide( 三)
- 【转】Gradle User Guide 中文版
- Kibana User Guide [4.2] » Getting Started with Kibana » Data Visualization: Beyond Discovery
- PhysX3 User Guide 02 - Shape
- 通过阅读Oracle Enterprise Asset Management User Guide,我对Oracle eAM的初步理解
- cilk之User Guide学习笔记(4)cilk_for的分析
- Docker—从入门到实践—Welcome to the Docker user guide
- oracle帮助文档——SQL*Plus User's Guide and Reference
- Understanding Your Users : A Practical Guide to User Requirements Methods, Tools, and Techniques
- SysLink UserGuide
- HTB Linux queuing discipline manual - user guide笔记
- GradleUserGuide中文版 1)介绍 2)概述 3)教程 4)安装 5)故障 6)构建基础
- mybatis_user_guide(3)XML配置