Groovy 学习笔记 (一)
来源:互联网 发布:java设计系统主界面 编辑:程序博客网 时间:2024/06/11 03:35
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() }
- Groovy 学习笔记 (一)
- Groovy学习笔记 一 、搭建
- Groovy学习笔记之入门一
- Groovy学习笔记(一)基本语法
- groovy学习笔记1
- Groovy学习笔记(1)
- Groovy学习笔记
- Groovy 学习笔记 (二)
- Groovy 学习笔记 (三)
- Groovy学习笔记-Groovlets
- Groovy 学习笔记
- Groovy学习笔记-基础
- groovy学习笔记
- groovy 学习笔记
- Groovy学习笔记
- groovy学习笔记
- 1groovy学习笔记
- groovy学习笔记
- 向数据库添加数据有三种方法利用 SQL语句添加、通过SqlParameter参数添加和通过存储过程添加。(三)
- 关于C++类库KYLib: 平衡二叉树类(AVL tree)
- 偷懒了
- 我的C++学习笔记
- 自定义控件的使用(.aspx调用.ascx)
- Groovy 学习笔记 (一)
- 推荐 OWASP - Transport Layer Protection Cheat Sheet
- 古堡惊魂
- 英文站SNS推广第一季
- 面向对象
- 各位大哥大姐介绍下深圳那边情况.....
- c# DataTable常用操作
- 心情不好
- Groovy 学习笔记 (二)