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操作符的更多相关文章

  1. groovy中的正则表达式操作符【groovy】

    groovy中对于正则表达式的书写进行了简化,同时引入了新的操作符,使得正则表达式使用起来比较方便简单. 对于书写的改进: 比如 assert "\\d" == /\d/ 也就是在 ...

  2. Groovy重载操作符

    重载一时爽,一直重载一直爽. 最近在读<Groovy in action>一本书重新复习了Groovy的一些语法特性,迷恋上这个重载操作符的功能,坚持爽的不要要的.分享一个Demo. 由于 ...

  3. 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 ...

  4. Groovy入门经典 随书重点

    1 数值和表达式 1.1数值 整数是Integer类的实例 有小数部分的数值是BigDecimal类的实例 不同于java,没有基础数据类型 一切皆对象的概念重于java 1.2表达式 两个整数的除法 ...

  5. Groovy入门教程

    Groovy入门教程 kmyhy@126.com  2009-5-13 一.groovy是什么 简单地说,Groovy 是下一代的java语言,跟java一样,它也运行在 JVM 中. 作为跑在JVM ...

  6. 30分钟groovy快速入门并掌握(ubuntu 14.04+IntelliJ 13)

    本文适合于不熟悉 Groovy,但想快速轻松地了解其基础知识的 Java开发人员.了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合.内置正则表达式和闭包. ...

  7. Groovy学习笔记(二)

    在上一篇文章中我们主要学习了如何搭建Groovy开发环境,为我们的Groovy之旅做好了准备工作,不知道你是否准备好了?接下来我们就一起看看Groovy与我们熟悉的Java有什么异同. Groovy是 ...

  8. atitit groovy 总结java 提升效率

    atitit groovy 总结java 提升效率 #---环境配置 1 #------安装麻烦的 2 三.创建groovy项目 2 3.  添加 Groovy 类 2 4.  编译运行groovy类 ...

  9. 【Groovy基础系列】 Groovy运算符

    ?运算符 在java中,有时候为了避免出现空指针异常,我们通常需要这样的技巧: if(rs!=null){ rs.next() … … } 在groovy中,可以使用?操作符达到同样的目的: rs?. ...

随机推荐

  1. shell脚本 批量转换目录下文件编码

    发布:JB01   来源:脚本学堂     [大 中 小] 分享一例shell脚本,实现可以批量转换目录下的文件编码,很实用的一个小shell,有需要的朋友参考下.原文地址:http://www.jb ...

  2. Django QuerySet 方法梳理 。model外键 多对多的保存

    引用:https://feifeiyum.github.io/2017/03/28/python-django-queryset/ 说明 Models 层是 Django 框架中最强大的部分之一, 大 ...

  3. Ubuntu 11.04 下安装配置 JDK 7

    第一步:下载jdk-7-linux-i586.tar.gz wget -c http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-i586 ...

  4. hive中创建hive-json格式的表及查询

    在hive中对于json的数据格式,可以使用get_json_object或json_tuple先解析然后查询. 也可以直接在hive中创建json格式的表结构,这样就可以直接查询,实战如下(hive ...

  5. css设置背景固定不滚动效果的示例

    css设置背景固定不滚动效果的示例 背景固定不滚动各位看到最多的无非就是QQ空间了,我们在很多的空间都可以看到内容滚动而北京图片不滚动了,下文整理了几个关于背景固定不滚动css代码. 一.css设置背 ...

  6. 004Maven_Pom.xml文档的介绍

    很重要的一个文档,具体介绍如下:

  7. 第二百七十九节,MySQL数据库-pymysql模块操作数据库

    MySQL数据库-pymysql模块操作数据库 pymysql模块是python操作数据库的一个模块 connect()创建数据库链接,参数是连接数据库需要的连接参数使用方式: 模块名称.connec ...

  8. CSS伪类选择器 - nth-child(an+b):

    CSS伪类选择器 - nth-child(an+b): 第一种:简单数字序号写法:nth-child(number)直接匹配第number个元素.参数number必须为大于0的整数.li:nth-ch ...

  9. maven 完整的settings.xml

    maven 完整的settings.xml <?xml version="1.0" encoding="UTF-8"?> <!-- Licen ...

  10. keyword static

    1. 不能通过类名来调用类的非静态成员函数 2. 类的对象可以使用静态成员函数和非静态成员函数 3. 静态成员函数中不能引用非静态成员 因为静态成员函数属于整个类, 在类的实例化对象之前就已经分配了空 ...