Groovy 学习笔记 (二)

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()
}

By javafuns on May 4, 2009 at 17:47 · Views: 3,266 · Permalink
Categorized in: Scripts · Tagged with: , , ,
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a Reply


  • Highest Rated

  • My PicasaPhotos

    IMG_0614.JPG

    IMG_0534.JPG

    monkey.jpeg

  • RSS My del.icio.us

  • My RSS