当在Groovy中使用数组作为参数调用带有varargs的方法时,在地球上处理的参数是什么?

时间:2015-08-11 07:43:55

标签: arrays groovy variadic-functions

它是原始数组或包含原始数组的单元素长数组。

正如GLS所述,它是原点:

  

如果使用数组作为参数调用varargs方法,则参数将是该数组,而不是包含给定数组作为唯一元素的长度为1的数组。

def foo(Object... args) { args }
Integer[] ints = [1, 2]
assert foo(ints) == [1, 2]

但是当我写这个片段并在GroovyConsole上执行时,

def foo(Integer... args) { args?.length }
assert foo(null) == null
assert foo() == 0
assert foo(0,1,2) == 3
assert foo([0,*(4..6)]) != 3

它给了我相反的答案:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[0, 4, 5, 6]' with class 'java.util.ArrayList' to class 'java.lang.Integer'
at sample.run(sample.groovy:107)

所以我在最后一个语句上传播数组,然后就可以了。

assert foo(*[0,*(4..6)]) != 3

1 个答案:

答案 0 :(得分:3)

致电时

foo([0,*(4..6)])    

然后[0,*(4..6)]是一个列表,而不是一个数组

尝试

foo([0,*(4..6)] as Integer[])