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?. ...
随机推荐
- linux下apache服务器的安装、启动、查看
一.apache的启动 apahce启动命令:/你的安装目录/apachectl start apaceh启动 apache停止命令/你的安装目录/apachectl stop 停止 apache ...
- 点滴积累【JS】---JS实现仿百度模糊搜索效果
效果: HTML代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="In ...
- "围观"设计模式(2)--里氏替换原则(LSP,Liskov Substitution Principle)
在面向对象的程序设计中.里氏替换原则(Liskov Substitution principle)是对子类型的特别定义.它由芭芭拉·利斯科夫(Barbara Liskov)在1987年在一次会议上名为 ...
- UNRECOGNIZED SELECTOR SENT TO INSTANCE 问题快速定位的方法
开发中常见的一类崩溃错误是遇到:unrecognized selector sent to instance 0xaxxxx…而backtrace又无法明确说明错误在哪行代码,如何快速定位BUG呢? ...
- DOM方法 getElementsByName()方法
http://www.imooc.com/code/1583 getElementsByName()方法 返回带有指定名称的节点对象的集合. 语法: document.getElementsByNam ...
- python操作word【简单封装】
#!/usr/bin/env python # -*- coding: utf-8 -*- import win32com.client import os #-------------------- ...
- Maven基础命令
Maven 参数 -D 传入属性参数 -P 使用pom中指定的配置 -e 显示maven运行出错的信息 -o 离线执行命令,即不去远程仓库更新包 -X 显示maven允许的debug信息 -U 强制去 ...
- 【BZOJ】1647: [Usaco2007 Open]Fliptile 翻格子游戏(暴力)
http://www.lydsy.com/JudgeOnline/problem.php?id=1647 自己太弱...看题解.. 竟然是枚举第一行的放法,,,因为一定要全部变0,所以将前一行1的在这 ...
- NYOJ 1009 So Easy[Ⅰ]【简单题】
/* 题目大意:求三角形的外接圆 解题思路:c/sin(C)=2R,先求出cos,在求出sin 关键点:直接调用库 解题人:lingnichong 解题时间:2014-10-18 10:19:33 解 ...
- WebGL中的OpenGL着色器语言
在webgl中,调用了OpenGL-ES-2.0的API,而在OpenGL-ES专为嵌入式设备设计,其和其它设备一样,都是使用GLSL(GL Shading Language)来编写片段程序并执行于G ...