Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy dot notation on lists

Tags:

syntax

groovy

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?

like image 825
Andrea Avatar asked Oct 07 '22 07:10

Andrea


1 Answers

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.

like image 53
Ted Naleid Avatar answered Oct 13 '22 12:10

Ted Naleid