简体   繁体   English

探究数组列表中的每个方法

[英]Groovy each method on list of arrays

I met quite strange behaviour of each method on list of arrays in groovy. 我在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. 因为变量行是具有一个元素的数组,这是我从列表中原来的2个元素的数组。

Is there some explanation for this? 有什么解释吗? Im using groovy 1.8.8 or 2.1.2 我正在使用groovy 1.8.8或2.1.2

I guess it's a feature rather than a bug :p 我想这是一个功能,而不是一个错误:p

Object[] in a closure declaration has a special semantic for variable argument: 闭包声明中的Object []对于变量参数具有特殊的语义:

From http://groovy.codehaus.org/Closures+-+Formal+Definition : 来自http://groovy.codehaus.org/Closures+-+Formal+Definition

Groovy has special support for excess arguments. Groovy对多余的参数有特殊的支持。 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. 在您的示例中,传递给闭包的参数将再次使用新的Object数组进行包装,该对象数组包含list作为唯一元素。

As an example: 举个例子:

def list = [
    [2, "foo"].toArray(),
    [4, "bar"].toArray()
]

def c = {Object[] args -> println args}
c(list)

Output: 输出:

[[[2, foo], [4, bar]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM