3

I just found that code:

[1,2] [4, 4]

is completely valid in Groovy but can't find what does such expression evaluates to, for me it returns null in all possible cases:

groovy:000> [1, 2] []
===> []
groovy:000> [1, 2] [4] 
===> null
groovy:000> [1, 2] [4,5]
===> [null, null]

So basically the question is what does the expression:

a = list1 list2

mean in Groovy?

1 Answer 1

6

In groovy, the [] operator is just a shorthand for getAt(), so in this case it's calling the method List.getAt(Collection).

The behavior is to return a list containing all the elements whose index is listed in the collection. So for [1,2][4,5], it's returning a list with elements 4 and 5, which both happen to be out of range, so null.

Here are some examples that illustrate it a little better:

assert ['a', 'b', 'c', 'd', 'e'][1, 3] == ['b', 'd']
assert [0, 1, 2, 3, 4][4..0] == [4, 3, 2, 1, 0]
Sign up to request clarification or add additional context in comments.

3 Comments

@MichaelRutherfurd Well, it usually won't make sense to use the subscript with a literal I think. def firstAndThird = [4,3,2,1][0,2] doesn't make too much sense, but def firstAndThird = someList[0,2] does a bit more :)
@MichaelRutherfurd BTW, I think you are right about this syntax being confusing, as it clashes with the parentheses-less method call syntax. foo.bar 1 means foo.bar(1), but foo.bar [1] does not mean foo.bar([1]). And foo.bar 1, 2 is legal syntax, but foo.bar [1], 2 yields a syntax error :). I think what is confusing is the parentheses-less syntax; it has many corner-cases that makes its usage ugly.
Scala has paren-less syntax so Groovy needs it too! Just keeping up with the Joneses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.