Groovy操作符
Groovy操作符
这一篇简单介绍一下Groovy中的操作符。
算数操作符
groovy支持java中的所有操作符,下面只列举一些groovy特有的:
** power运算符,也叫次方。
assert 2 ** 3 == 8
**= power的一元运算
def f = 3
f **= 2
assert f == 9
类操作符
Safe navigation operator(安全导航符)用于避免空指针。当不确定一个类是否是空指针的时候使用。
def person = Person.find { it.id == 123 }
def name = person?.name
assert name == null
Direct field access operator
class User {
public final String name
User(String name) { this.name = name}
String getName() { "Name: $name" }
}
def user = new User('Bob')
assert user.name == 'Name: Bob'
在groovy中,user.name会调用对应的getName()方法,这是groovy的一个语法特性,后面的章节再将。如果想要直接使用这个属性可以这么写:
assert user.@name == 'Bob'
Method pointer operator
.&用于将被调用的方法存入一个方法变量中,接着只要调用这个变量就相当于调用之前的那个方法。直接看代码:
def str = 'example of method reference'
def fun = str.&toUpperCase
def upper = fun()
assert upper == str.toUpperCase()
上面的代码将str的toUpperCase方法存入了fun中,接着调用fun等于调用了str的toUpperCase方法。
正则表达式
Pattern operator
模式操作符使用~,~后面加字符串用于创建java.util.regex.Pattern实例。
def p = ~/foo/
p = ~'foo'
p = ~"foo"
p = ~$/dollar/slashy $ string/$
p = ~"${pattern}"
assert p instanceof Pattern
Find operator
查询操作符使用=~,在字符串上调用=~会生成java.util.regex.Matcher实例。
def text = "some text to match"
def m = text =~ /match/
assert m instanceof Matcher
if (!m) {
throw new RuntimeException("Oops, text not found!")
}
Match operator
匹配操作符使用==~表示,返回结果是Boolean类型。
m = text ==~ /match/
assert m instanceof Boolean
if (m) {
throw new RuntimeException("Should not reach that point!")
}
其他操作符
Spread operator
展开操作符*.,用于收集列表中的一些公共属性,然后将他们合成一个新的列表:
class Car {
String make
String model
}
def cars = [
new Car(make: 'Peugeot', model: '508'),
new Car(make: 'Renault', model: 'Clio')]
def makes = cars*.make
assert makes == ['Peugeot', 'Renault']
Range operator
范围操作符使用..
def range = 0..5
assert (0..5).collect() == [0, 1, 2, 3, 4, 5]
assert (0..<5).collect() == [0, 1, 2, 3, 4]
assert (0..5) instanceof List
assert (0..5).size() == 6
Spaceship operator
比较操作符<=>,内部其实是调用了compareTo方法:
assert (1 <=> 1) == 0
assert (1 <=> 2) == -1
assert (2 <=> 1) == 1
assert ('a' <=> 'z') == -1
Membership operator
成员关系操作符in,相当于调用isCase方法,在List中,相当于contains方法:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)
也可以使用list.contains('Emmy') or list.isCase('Emmy')
Identity operator
身份操作符is用于判断两个引用是否相同。相当于在java中的==,而在groovy中==相当于equals方法。
def list1 = ['Groovy 1.8','Groovy 2.0','Groovy 2.3']
def list2 = ['Groovy 1.8','Groovy 2.0','Groovy 2.3']
assert list1 == list2
assert !list1.is(list2)
Coercion operator
强制操作符as,用于不同类型的转换:
Integer x = 123
String s = x as String
如果要给自定义的类实现强制转换,需要asType方法:
class Identifiable {
String name
}
class User {
Long id
String name
def asType(Class target) {
if (target==Identifiable) {
return new Identifiable(name: name)
}
throw new ClassCastException("User cannot be coerced into $target")
}
}
def u = new User(name: 'Xavier')
def p = u as Identifiable
assert p instanceof Identifiable
assert !(p instanceof User)
Call operator
Call操作符使用(),用来调用call这个方法,如下:
class MyCallable {
int call(int x) {
2*x
}
}
def mc = new MyCallable()
assert mc.call(2) == 4
assert mc(2) == 4
操作符重载
groovy中支持操作符重载,重载操作符很简单,只要实现对应的方法即可,如+只要实现plus方法:
class Bucket {
int size
Bucket(int size) { this.size = size }
Bucket plus(Bucket other) {
return new Bucket(this.size + other.size)
}
}
def b1 = new Bucket(4)
def b2 = new Bucket(11)
assert (b1 + b2).size == 15
结尾
关于groovy操作符的详细用法请参考:http://www.groovy-lang.org/operators.html
Groovy操作符的更多相关文章
- groovy中的正则表达式操作符【groovy】
groovy中对于正则表达式的书写进行了简化,同时引入了新的操作符,使得正则表达式使用起来比较方便简单. 对于书写的改进: 比如 assert "\\d" == /\d/ 也就是在 ...
- Groovy重载操作符
重载一时爽,一直重载一直爽. 最近在读<Groovy in action>一本书重新复习了Groovy的一些语法特性,迷恋上这个重载操作符的功能,坚持爽的不要要的.分享一个Demo. 由于 ...
- Groovy中的操作符重载
操作者 方法 a + b a.plus(b)中 a - b a.minus(b)中 a * b a.multiply(b)中 a ** b a.power(b)中 a / b a.div(b)中 a ...
- Groovy入门经典 随书重点
1 数值和表达式 1.1数值 整数是Integer类的实例 有小数部分的数值是BigDecimal类的实例 不同于java,没有基础数据类型 一切皆对象的概念重于java 1.2表达式 两个整数的除法 ...
- Groovy入门教程
Groovy入门教程 kmyhy@126.com 2009-5-13 一.groovy是什么 简单地说,Groovy 是下一代的java语言,跟java一样,它也运行在 JVM 中. 作为跑在JVM ...
- 30分钟groovy快速入门并掌握(ubuntu 14.04+IntelliJ 13)
本文适合于不熟悉 Groovy,但想快速轻松地了解其基础知识的 Java开发人员.了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合.内置正则表达式和闭包. ...
- Groovy学习笔记(二)
在上一篇文章中我们主要学习了如何搭建Groovy开发环境,为我们的Groovy之旅做好了准备工作,不知道你是否准备好了?接下来我们就一起看看Groovy与我们熟悉的Java有什么异同. Groovy是 ...
- atitit groovy 总结java 提升效率
atitit groovy 总结java 提升效率 #---环境配置 1 #------安装麻烦的 2 三.创建groovy项目 2 3. 添加 Groovy 类 2 4. 编译运行groovy类 ...
- 【Groovy基础系列】 Groovy运算符
?运算符 在java中,有时候为了避免出现空指针异常,我们通常需要这样的技巧: if(rs!=null){ rs.next() … … } 在groovy中,可以使用?操作符达到同样的目的: rs?. ...
随机推荐
- CentOS 7.0 关闭firewalld防火墙指令 及更换Iptables防火墙
CentOS 7.0 关闭firewalld防火墙指令 及更换Iptables防火墙 时间:2014-10-13 19:03:48 作者:哎丫丫 来源:哎丫丫数码网 查看:11761 评论:2 ...
- 虚拟机下安装centos7方法,修改系统语言为简体中文的方法
说明 自己装系统时一般都可以自定义选择系统语言.可是云端服务器一般都是安装好的镜像,默认系统语言为英文,对于初学者可能还会有搞不懂的计算机词汇.这里简单说一下centos7怎么修改系统语言为中文. 虚 ...
- 安装语言包(LANGUAGE PACKAGE)
by 枫竹丹青 一.说明 在SAP ECC 安装好后,如果是生产版本,通常只有两种语言--英语和德语.这时如需中文环境,则需定义支持的语言类型并导入语言包.如果安装的是IDES版,则系统中已包含了几十 ...
- Ecshop安装的坑,建议不要使用!
最近因为工作的需要,安装了下ecshop,这个曾经的火爆开源程序,现在也呈现出疲态. 1.请看官方的运行环境推荐: 服务器端运行环境推荐·php版本5.0以上5.3以下的版本(推荐使用5.2系列版本) ...
- 基于jQuery左侧小图滚动右侧大图显示代码
今天给大家分享一款 jQuery左侧小图滚动右侧大图显示代码是一款基于jQuery实现的左侧滚动图片点击大图查看效果代码.该实例适用浏览器:IE8.360.FireFox.Chrome.Safari. ...
- C语言 · 删除数组中的0元素
算法提高 6-9删除数组中的0元素 时间限制:1.0s 内存限制:512.0MB 编写函数CompactIntegers,删除数组中所有值为0的元素,其后元素向数组首端移动.注意,C ...
- JDK1.8与spring3.x的不兼容
今天运气很好,两次遇到了这个兼容性问题,spring3.x不支持 java 1.8 byte code format!! 九月 10, 2017 7:17:18 上午 org.apache.catal ...
- KMP + 求相等前后缀--- POJ Seek the Name, Seek the Fame
Seek the Name, Seek the Fame Problem's Link: http://poj.org/problem?id=2752 Mean: 给你一个字符串,求这个字符串中有多少 ...
- 获取checkbox 组成字符串
<input type="checkbox" id="goods_server_name" name="goods_server_name[]& ...
- CSS浮动与清除浮动(overflow)例子
在css中浮动与清除浮动功能是我们开发中常用到的一个功能了,下面小编来为各位分析关于CSS浮动与清除浮动(overflow)例子吧. float脱离文本流,可是为什么文字却会有环绕的效果,这点实在是神 ...