我是靠谱客的博主 伶俐红酒,这篇文章主要介绍Groovy的展开操作符(Spread Operator)*.和*,现在分享给大家,希望可以做个参考。

*.“操作符称之为:spread-dot操作,即“展开(点)”操作。比如

复制代码
1
list*.member

复制代码
1
list.collect{ item -> item?.member }

是等效的。此处member可以是属性,也可以是get/set方法,甚至是一般的方法。如下例

复制代码
1
2
3
4
5
6
class SpreadDotDemo { def count } def list = [new SpreadDotDemo(count:1),new SpreadDotDemo(count:2),new SpreadDotDemo(count:5) ] assert 8==list*.count.sum() assert 8==list.count.sum()//去掉*也可以的

*.”也是安全解引用操作符(Safe Dereference Operator也称为提领运算符),用以避免NullPointerException

复制代码
1
2
3
def SpreadDotDemo demo demo.count //将抛空指针异常 demo*.count //避免了null的检查,并返回null

跟spead doc操作符相关的事spead操作(*),它可以看作是逗号分隔的list的下标操作符的逆操作

复制代码
1
2
3
4
5
6
7
def getList(){ return [1,2,3] } def sum(a,b,c){ return a + b + c } assert 6 == sum(*list)

看到了吧,示例中将list又展开为三个单独的元素

最后

以上就是伶俐红酒最近收集整理的关于Groovy的展开操作符(Spread Operator)*.和*的全部内容,更多相关Groovy的展开操作符(Spread内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部