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. Swift 的 pod 第三方库

    #HTTPpod 'Alamofire' #Elegant HTTP Networking in Swiftpod 'SwiftHTTP' #Thin wrapper around NSURLSess ...

  2. CentOS 5.4 安装和卸载桌面

    显示系统已经安装的组件,和可以安装的组件:#yum grouplist 如果系统安装之初采用最小化安装,没有安装xwindow,那么先安装:#yum groupinstall "X Wind ...

  3. Cocos2d-x 3.4 初体验——安装教程

    电脑系统window7 32位 1.首先从官网下载cocos2d-x并解压 http://cn.cocos2d-x.org/download/ 解压后的文件夹中有一个setup.py,双击运行.需要安 ...

  4. 页面跳转时候拼接在url后面的多个 参数获取

    function GetRequest() { var url = location.search; var theRequest = new Object(); if (url.indexOf(&q ...

  5. jquery 获取绑定事件

    在1.8.0版本之前,我们要想获取某个DOM绑定的事件处理程序可以这样: 1 $.data(domObj,'events');//或者$('selector').data('events') 而从1. ...

  6. 华农校赛--G,用set比较大小,缩短时间复杂度

    Array C Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 581  Solved: 101[Submit][Status][Web Board] D ...

  7. Unity3D学习(十一):关于UI销毁后图集仍然无法释放问题的解决办法

    前言 最近进行项目性能优化的时候发现的问题. 问题 从大厅进到单局的过程中,会经过选择英雄和加载两个流程,这两个流程对应的UI界面都会有一张几mb左右的贴图作为背景,在进入单局游戏后这两个UI已经销毁 ...

  8. webservice文件上传下载

    使用DataHandler实现webservice的文件上传下载 服务端代码: package com.hello.weChat.controller; import javax.activation ...

  9. am335x -- kio 控制接口

    //example #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include < ...

  10. 让 MySQL 支持 emoji 存储

    要让 MySQL 开启 utf8mb4 支持,需要一些额外的设置. 1. 检查 MySQL Server 版本 utf8mb4 支持需要 MySQL Server v5.5.3+ 2. 设置表的 CH ...