列表上的Groovy点表示法 [英] Groovy dot notation on lists

查看:112
本文介绍了列表上的Groovy点表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



每当你有一个东西的集合,称它为 items

code>,只需通过访问该集合上的该属性即

 项目,就可以映射属性。 prop == items.collect {it.prop} 

这对我来说很奇怪,因为我会想第一个表示法实际上意味着我想访问集合对象本身的属性。真实的模糊情况可能会发生,例如:
$ b $ pre $ [[1,2,3],['cat','elephant' ]]。size == 2

但根据以前的记法,它应该等于 [3,2]



此外,如果收集符号不够短,则有 * 。传播点运算符的意思是准确地用这种方式:

  [[1 ,2,3],['cat','elephant']] *。size = [3,2] 




歧义点符号的用途是什么?是否仅仅为保存 *。上的字符而添加,或者它具有合法的使用情况,其中 *。不起作用和 collect 会很麻烦吗?



解决方案

<我前一段时间写了一篇博客文章,名为Groovy Spread Operator Optional For Properties,可以深入了解这种情况下所发生的情况。



简短的回答是,它是更多的语法糖,并最终调用 DefaultGroovyMethods.getAt(Collection,String)



它没有任何巨大的优势,但它可以使一些DSL更容易编写,因为它们可以操作correc tly该对象是一个集合还是一个对象。


I am not understanding the purpose of the following construction in Groovy.

Whenever you have a collection of stuff, call it items, you can map over an attribute just by accessing that attribute on the collection, that is,

items.prop == items.collect { it.prop }

This looks weird to me, because I would think that the first notation actually meant that I want to access a property on the collection object itself. Real cases of ambiguity can happen, for instance

[[1,2,3],['cat', 'elephant']].size == 2

but according to the previous notation it should equal [3, 2].

Moreover, if the collect notation was not short enough, there is the *. spread-dot operator which is meant to be used exactly in this way:

[[1,2,3],['cat', 'elephant']]*.size = [3, 2]

What is the purpose of the ambiguous dot notation? Was it just added to save on character over *. or it has legitimate cases of use where *. would not work and collect would be cumbersome?

解决方案

I wrote a blog post a while ago called "Groovy Spread Operator Optional For Properties" that dives into what's going on under the covers in this situation.

The short answer is, it's more syntactic sugar and eventually calls into DefaultGroovyMethods.getAt(Collection, String).

There aren't any huge advantages to it, but it could make some DSLs a little easier to write as they can operate correctly whether the object is a collection or a single object.

这篇关于列表上的Groovy点表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆