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 andcollect
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With