Groovy基础教程[翻译]

Groovy语言的一些基础操作以及一些简单的代码例子,这是官方网站翻译的文章。

Groovy语言上运行的Java运行时环境,它运行在几乎任何计算机系统,如Windows,Linux和Mac。

如果没有安装Groovy的运行环境,请安装哦。

Groovy代码注释

在Groovy中注释可以分为:单行注释、多行注释。

// comment like this to end of line, ignoring */ and /* and " and "

/*or comment like this, ignoring // and " and " until: */

/*or comment over
many lines, /*with no nesting*/

Groovy 字符串操作

"A string can be within single quotes on one line..."

"""...or within triple single quotes
over many lines, ignoring // and */ and /* comment delimiters,..."""

"...or within double quotes..."

"""...or within triple double quotes
over many lines."""

字符串操作多种多样子,可以清楚的感受到groovy给我们带来的简洁。

println "hello, world" // 打印新的一行

print "hello, worldn" //"print" 不会打印新的一行。
                       // 换行 ("n" on Unix/Linux, "rn" on Windows)

println "hello" + ", " + "world" // 字符串拼接

print "hello, "; println "world"

println( "hello, world" ) // 调用函数,传递参数

def a= "world"; println "hello, " + a //"def" 声明变量,打印

print "hello, world"; println() // 无参函数

def b= "hello", c= "world"; println "$b, ${c}"
//$ 在打印字符串获取变量值

groovy 整型和小数的计算

def g = 7, groovy = 10.2
// 通过def定义多个变量

print g + ", " + groovy + "n"
//prints: 7, 10.2


assert g + ", " + groovy == "7, 10.2"
// assert 断言声明操作判断是否和我们预期值相同

更多运算符操作

assert 4 * ( 2 + 3 ) - 6 == 14 // 整型

assert 2.5 + 7 == 9.5

print 7/3+"n" // 打印:2.3333333333 ,保留小数位十位

print 7/4+"n" // 打印:1.75

assert 7 / 4 == 1.75 //decimal number or division converts expression to decimal

Groovy 逻辑运算符

assert 2 > 3 == false
assert 7 <= 9
assert 7 != 2
assert true
assert ! false
assert 2 > 3 || 7 <= 9
assert ( 2 > 3 || 4 < 5 ) && 6 != 7

Groovy 变量的多种使用

变量名称规则这里就不做探讨了,因为Groovy和Java无差别。

// 声明变量a,但没有赋值,默认值为null
def a
assert a == null


// 弱类型语言的优势,可以赋值整型也可以赋值字符串
def b = 1
assert b == 1
b = 2
assert b == 2 // 变量重新赋值

b = "cat"
assert b == "cat" // 重新赋值不同数据类型
b = null
assert b == null // 不分配任何值
// Groovy类的静态常量的值
assert Byte.MAX_VALUE == 127

// 字符串转换为Byte字节
assert Byte.parseByte("34") == 34

// 创建字节对象
def b= new Byte("34")

assert b.intValue() == 34

Groovy数据类型判断

assert 4.class == Integer //the common types have both a short name...
assert 4.class == java.lang.Integer //...and a long name
assert 4.5.class == BigDecimal
assert "hello, world".class == String
def a= 7
assert a.class == Integer

Groovy声明导入类

对于有的类来说,我们需要通过import关键字来导入对应的类路径,比如说:”java.text.DecimalFormat”

一些内置的类路径我们不需要导入,比如说String

import java.text.*
assert new DecimalFormat( "#,#00.0#" ).format( 5.6789 ) == "05.68"

Groovy异常处理

try{
  "moo".toLong() // 这里将抛出异常
  assert false
      //this code should never be reached, so will always fail if executed
}catch(e){
    assert e instanceof NumberFormatException
}
// 我们可以通过 "instanceof" 关键字来检查类型,避免异常。

Groovy中的List和Map类型

List集合有点像数组

// 定义集合
def list= [1, 2, 3]
list= [] // 空list集合
list= [1, "b", false, 4.5 ] // 混合类型存放值
assert list[0] == 1 && list[1] == "b" && ! list[2] && list[3] == 4.5 // 通过索引来改变引用


def map= [1:"a", 2:"b", 3:"c"] //map indicated with colon :
map= [:] //empty map
map= ["a": 1, "b": "c", "groovy": 78.9, 12: true] //混合类型存放值
assert map["a"] == 1 && map["b"] == "c" && map["groovy"] == 78.9 && map[12] // 通过key来改变引用


// 通过"each"方式来遍历list和map:

// list集合的遍历,通过it来获取当前值
[ 2, -17, +987, 0 ].each{
  println it
}

// 我们还可以自定义那个it,也就是自定义参数名称来存放当前值
// 需要注意的语法格式
[ 2, -17, +987, 0 ].each{ n ->
  println n
}

// 遍历map对象,通过两个参数来存放当前值
// 需要注意的语法格式
[ 1: 3, 2: 6, 3: 9, 4: 12 ].each{ k, v->
  assert k * 3 == v
}

Groovy范围类型 Range

( 3..7 ).each{ println it }  //打印 3, 4, 5, 6, and 7
( 3..<7 ).each{ println it } //打印 3, 4, 5, and 6 //excludes 7
来源: 雨林博客(www.yl-blog.com)