Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply array to array in Groovy

Tags:

list

groovy

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?

like image 795
Nutel Avatar asked May 16 '26 04:05

Nutel


1 Answers

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]
like image 94
ataylor Avatar answered May 19 '26 01:05

ataylor