groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <>
Subject Re: Assigning "leftover" args to trailing array, difference between func params and plain assignment
Date Thu, 13 Aug 2015 08:31:29 GMT
On 13 August 2015 at 07:11, KARR, DAVID <> wrote:
> Based on a question I saw on IRC, it appears that the way values are allocated to parameters
differs between two cases, where one case is calling a function, and the other is an "inline"

I don't think those two cases are equivalent.

> In other words, comparing these two different cases:
>         def foo(Object a, Object[] b) { println("a[${a}] b[${b}]") }
> And calling it with:
>         foo(1, 2, 3, 4)

That would be the same as Java's: `void foo(Object a, Object... b) {
/* ... */ }`

> And the following case:
>         def (int a, int[] b) = [1, 2, 3, 4]                   // Given this ...
>         println("a[$a] b[$b]")

No Java equivalent here ;-)

> Putting this all into a script, this outputs this:
>         a[1] b[[2, 3, 4]]
>         a[1] b[[2]]
> Apparently, the ability to allocate the "rest" of the values to a trailing array parameter
works fine for function parameters, but for the other case (what would you call that?), it
just puts the first value into the array.

It is called multiple assignment.

As I said above, those two features are unrelated. In the case of
multiple assignment, Groovy takes one value at the time from the right
side and assigns it to the next variable from the left side,
performing type conversions if needed. The process stops when there
are no more variables on the left side. If the right side has fewer
elements than there are variables on the left side, the remaining
variables will be set to `null`. In order for this to work an object
on the right side must have a method `getAt(int)`.

More details about multiple assignment can be found here:

Variable number of arguments are described here:


View raw message