Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asterisks in front of array names in Groovy?

Tags:

groovy

I'm a bit new to Groovy, so I'm sure this is one of those extremely obvious things...but it's difficult to search for via Google.

In other languages, asterisks tend to represent pointers. However, in this snippet of Groovy code:

byte[] combineArrays(foo, bar, int start) {
  [*foo[0..<start], *bar, *foo[start..<foo.size()]]
}

I can only imagine that that's not the case. I mean, pointers? Groovy?

I'm assuming that this code intends to pass the members of foo and bar as opposed to a multidimensional array. So what exactly do the asterisks mean?

Thanks a lot for your help.

like image 212
WildM Avatar asked Jan 09 '12 15:01

WildM


1 Answers

When used like this, the * operator spreads a List or Array into a list of arguments. That didn't help at all, did it? How about an example instead? Say we have this function:

def add(Number a, Number b) {
  return a + b
}

And this List

def args = [1, 2]

We shouldn't do this:

add(args)

because the function expects two numeric arguments. But we can do this:

add(*args)

because the * operator converts the List of 2 elements into 2 arguments. You can use this operator with Lists and Arrays.

like image 115
Dónal Avatar answered Oct 06 '22 02:10

Dónal