Groovy 学习笔记 (一)

1. 关于字符串:

 

简单字符串可以用单引号和双引号, 但如果使用GString, 则必须使用双引号. 比如 $foo, hello world

 

多行字符串则可以使用 “”" (3个双引号), 例如:

 

def text = “”"/

hello there ${name}

how are you today?

“”"

如果对这个text进行输出,会发现输出是按原样式输出的,即换行符也输出. 这在处理类似 HTML 代码时时特别有用的.

另外, 可以使用 // 来定义字符串, : def basename = /[Strings and GString^//]+$/

在这种情况下, 只需对 / 进行转义: //; 但如下定义是不合法的:def x = //, 可以这么写: def x = /${}/

 

2.字符串操作:

 

a). 字符串加减操作

 

def string = ‘hippopotamus’

 

print string hippo mus + to == potato  // 果然强悍!!!

 

b).字符串转化为字符数组

 

apple’.toList()

 

def  string = “an apple a day”

 

assert string.toList().unique().sort().join() == ‘ adelnpy’

 

c).字符串反转

 

assert’string’.reverse() == ‘gnirts’

 

def string = ‘Yoda said, “can you see this?”‘

 

def revwords= string.split(’ ‘).toList().reverse().join(’ ‘)

 

assert revwords== ‘this?” see you “can said, Yoda’

 

d).字符串查找

 

def words = ['bob', 'alpha', 'rotator', 'omega', 'reviver']

 

def bigPalindromes = words.findAll {w -> w == w.reverse() && w.size() > 5}

 

assert bigPalindromes == ['rotator', 'reviver']

 

3. 数字

 

a). 一切皆为对象, 数字也不例外

 

b). 对于非整型数字, 使用 BigDecimal 作为默认类型

 

4. 日期

 

可以直接对日期操作: def date = new Date() + 1

 

还可以:

 

use(TimeCategory) {

 

println new Date() + 1.hour + 3.weeks -2.days

 

}

 

其中 TimeCategory org.codehaus.groovy.runtime.TimeCategory

 

5. 方法调用: 方法调用时, 括号是可选的. 例如: print hello, world

 

6. 方法返回值: 默认最后一句就是方法的返回值, 也就是说, 最后一句的return语句是可有可无的. 当然, 如果在方法中间需要return, 还是要写 return 语句才行.

 

7. 闭包(closure): 闭包可以访问与闭包定义在同一scope的变量. 例如:

 

def name = “” //initialize variable

 

def printName = { println “The string in the name variable is ” + name } //define method

 

name = “Youssef” //set string Youssef in variable name

 

printName() //result: The string in the name variable is Youssef

 

如果不在同一scope, 那么需要给闭包指明参数, 参数与闭包的body部分用 -> 符号分隔. 如果只有一个参数, 则该参数可不必明确写出来, 默认用 it 作为该参数的名称.

 

def name = “” //initialize variable

 

def printName = { println “The string in the name variable is ” + it } //define method

 

name = “Youssef” //set string Youssef in variable name

 

printName(name) //result: The string in the name variable is Youssef

 

8. 异常处理: 不是强制性的

 

9. methodMissing propertyMissing 方法:

 

10. categories:

 

class StringCategory {

static String lower(String string) {

return string.toLowerCase()

}

}

 

 

use (StringCategory) {

assert "test" == "TeSt".lower()

}

 

 

 

猜你喜欢

转载自blog.csdn.net/goldtoad/article/details/4711664
今日推荐