groovy-运算符

时间:2022-09-14 23:48:07

算术和条件运算符

Groovy支”!”操作符,例如:

1 def expression = false
2 assert !expression

基于集合的运算符:

Spread Operator (*.)运算法:

spread操作符用来调用集合中的每一个对象的行为,就相当于调用collect方法一样:

1 parent*.action //equivalent to:
2 parent.collect{ child -> child?.action }

这个行为可能是一个方法调用或者属性访问,并返回一个列表。下面是一个例子:

1 assert ['cat''elephant']*.size() == [38]

我们也可以自定义这个运算符的行为:

1 class Person { String name }
2 class Twin {
3  Person one, two
4  def iterator() {
5  return [one, two].iterator()
6  }
7 }
8  
9 def tw = new Twin(one: new Person(name:'Tom'),
10  two: new Person(name:'Tim'))
11 assert tw*.name == ['Tom''Tim']
12 // expanded equivalent of above:
13 assert tw.collect{ it.name } == ['Tom''Tim']
Java field (.@):

Groovy自动的为所有的字段属性创建getter方法来返回字段属性的引用:

1 class X
2 {
3  def field
4 }
5  
6 x = new X()
7 x.field = 1
8 println x.field // 1

当然,你也可以根据自己的需求重载这个getter方法:

1 class X
2 {
3  def field
4  
5 def getField()
6  {
7  field += 1
8  }
9 }
10  
11 x = new X()
12 x.field = 1
13 println x.field // 2

@运算符容许你重载这个行为并且直接访问字段,所以我们可以将上面的代码扩展为:

1 println x.@field // 1

但是并不推荐这种方法。官方给我解释是:

It should be mentioned that, while interesting, this is probably not a good thing to do unless you really need to. Overriding a public interface to access the internal state of an object probably means you are about to break something. Not even recommended for use in tests since it increases coupling unnecessarily.

其他的操作符:

getAt(index)和putAt(index, value)对应于下标操作符,比如 foo[1] or foo['bar'],需要注意的是下标可以是int也可以是string。

Range操作符(..)类似于Python中的range函数,容许你创建一个序列。

isCase()操作符对应于in

Elvis Operator (?: )

这个操作符是java中三元操作符的另外一种形式,比如:

1 def displayName = user.name ? user.name : "Anonymous" //traditional ternary operator usage
2  
3 def displayName = user.name ?: "Anonymous" // more compact Elvis operator - does same as above

Safe Navigation Operator (?.)

好吧,我把它翻译为安全导航操作符,这个操作符主要是为了避免在你访问一个对象的属性或者方法的时候,出现 NullPointerException的问题。在java中当我们访问一个对象(这个对象值为null)的属性或者方法,会出现空指针异常,如果使用这个操作符,就不会出现空指针异常,而是会返回null。

1 def user = User.find"admin" //this might be null if 'admin' does not exist
2 def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown

正则表达式操作符

  • find (=~)
  • match (==~)
这两个操作符以后再说。
下面的表格列出了大量的操作符:

Operator Name

Symbol

Description

Spaceship

<=>

Useful in comparisons, returns -1 if left is smaller 0 if == to right or 1 if greater than the right

Regex find

=~

Find with a regular expresion? See Regular Expressions

Regex match

==~

Get a match via a regex? See Regular Expressions

Java Field Override

.@

Can be used to override generated properties to provide access to a field

Spread

*.

Used to invoke an action on all items of an aggregate object

Spread Java Field

*.@

Amalgamation of the above two

Method Reference

.&

Get a reference to a method, can be useful for creating closures from methods

asType Operator

as

Used for groovy casting, coercing one type to another.

Membership Operator

in

Can be used as replacement for collection.contains()

Identity Operator

is

Identity check. Since == is overridden in Groovy with the meaning of equality we need some fallback to check for object identity.

Safe Navigation

?.

returns nulls instead of throwing NullPointerExceptions

Elvis Operator

?:

Shorter ternary operator

groovy-运算符的更多相关文章

  1. groovy运算符

    import java.util.regex.Matcher /** * Created by Jxy on 2018/12/20 10:29 * groovy运算符 */ /*class opera ...

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

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

  3. groovy–运算符重载

    Groovy支持运算符重载,各种运算符被映射到普通的java对象的方法调用,这就使得开发者可以利用运算符重载的优势来编写自己的Java或者groovy对象. 下面的表格描述了groovy中的操作符所映 ...

  4. Groovy基本类型与运算符

    字符串 1.1字符串段落 def s = """Groovy Grails JAVA """ 输出结果: Groovy Grails JAV ...

  5. 看懂Gradle脚本(4)- Groovy语法之运算符重载

    继续讨论Task定义 回想一下前一篇文章的样例: task myTask { doLast { println 'hello world!' } } 这段脚本定义了一个名为myTask的任务.而且通过 ...

  6. groovy实现循环、交换变量、多赋值、?&period;运算符

    /** * Created by Jxy on 2019/1/3 10:01 * 1.实现循环的方式 * 2.安全导航操作符---?. * 3.一次性赋值给多个变量 */ 0.upto(2){ pri ...

  7. Groovy入门经典 随书重点

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

  8. Groovy入门教程

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

  9. atitit groovy 总结java 提升效率

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

  10. Groovy新手教程

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

随机推荐

  1. VR内容定制请找北京动软VR团队,长年承接VR&sol;AR应用、游戏内容定制

    最近这一拔VR及AR浪潮得到业界的热捧,与2015年年底到2016年年初乐相.蚁视.睿悦.焰火工坊等VR创业公司,陆续发布融资的信息不无关系.业界也有统计数据称,约90%的VR投资案例,发生在2015 ...

  2. &lbrack;问题2014A13&rsqb; 解答

    [问题2014A13]  解答 先引入两个简单的结论. 结论 1  设 \(\varphi\) 是 \(n\) 维线性空间 \(V\) 上的线性变换, 若存在正整数 \(k\), 使得 \(\math ...

  3. P问题、NP问题和NPC问题

    P问题.NP问题和NPC问题 这或许是众多OIer最大的误区之一.    你会经常看到网上出现“这怎么做,这不是NP问题吗”.“这个只有搜了,这已经被证明是NP问题了”之类的话.你要知道,大多数人此时 ...

  4. 排序算法总结(一)插入排序【Insertion Sort】

    最近在忙着找工作,以前看的排序算法都忘记了,悲剧啦T  T现在来回顾一下吧. 这边推荐一个算法可视化的网站,非常有用.http://visualgo.net/ 一.插入排序的思想(Wikipedia) ...

  5. 【转】iOS屏幕适配

    一.iOS屏幕适配发展历程 设备 适配技术 4及以前(iPad未出) 直接用代码计算 有了iPad autoResizing 有不同屏幕的iPhone后 autoLayout 有更多不同屏幕的iPho ...

  6. 阿里UX矢量图标库–最强大的矢量图标库(Icon font制作力荐工具)

    继前面介绍过ICON-FONT的制作后,找了几个ICON库都是国外的今天偶然发现阿里巴巴的图标矢量库,www.iconfont.cn用了之后感觉很强大,丰富的图标库(集合阿里妈妈&淘宝的图标库 ...

  7. ControlStyles(枚举)

    指定控件的样式和行为. 此枚举有一个 FlagsAttribute 特性,通过该特性可使其成员值按位组合.属性: ContainerControl:如果为true,则控件是类似容器的控件. UserP ...

  8. 敏捷开发(五)- 框架SCRUM内容

    本文主要是为了检测你对SCRUM的了解和使用程度,通过本文你可以检测一下     1.你们的SCRUM项目中各个角色是否合格,    2.SCRUM上面需要的会议是否有遗留,会议过程是否正确    3 ...

  9. 遇到bug我会怎么做

    我今天遇到一个问题,ztree显示数据,本来这个功能是没有问题的,但是当我新加入了几个页面筛选条件时,将集合传入ztree ,页面缺一直没显示出来,弄了两个小时,代码我都仔细排查了一次,发现没有问题, ...

  10. dubbo监控中心与admin管理项目的使用

    监控中心与admin管理项目都是针对特定的注册中心进行监控,因此需要配置对应的注册中心的地址,或者在dubbo.properties或者在applications.properties文件配置. == ...