I met quite strange behaviour of each method on list of arrays in groovy. I have given piece of code.
def list = [
[2, "foo"].toArray(),
[4, "bar"].toArray()
]
list.each { def row ->
println(row.length)
}
Which gives me pretty expecting result in console
2
2
Then I did small modification to this code
def list = [
[2, "foo"].toArray(),
[4, "bar"].toArray()
]
list.each { Object[] row ->
println(row.length)
}
And result is
1
1
Because variable row is array with one element which is my original 2 elements array from list.
Is there some explanation for this? Im using groovy 1.8.8 or 2.1.2
I guess it's a feature rather than a bug :p
Object[] in a closure declaration has a special semantic for variable argument:
From http://groovy.codehaus.org/Closures+-+Formal+Definition :
Groovy has special support for excess arguments. A closure may be declared with its last argument of type Object[]. If the developer does this, any excess arguments at invocation time are placed in this array. This can be used as a form of support for variable numbers of arguments.
In your example, the argument passed to the closure will be wrapped again with a new Object array, containing list
as the only element.
As an example:
def list = [
[2, "foo"].toArray(),
[4, "bar"].toArray()
]
def c = {Object[] args -> println args}
c(list)
Output:
[[[2, foo], [4, bar]]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.