当在 Groovy 中使用数组作为参数调用具有可变参数的方法时,究竟将参数视为什么?

When a method with varargs is called with an array as argument in Groovy, what's the argument treated as on earth?

要么是原始数组,要么是包含原始数组的单元素长数组。

正如GLS所说,这是起源之一:

If a varargs method is called with an array as an argument, then the argument will be that array instead of an array of length one containing the given array as the only element.

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

当你打电话时

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

那么[0,*(4..6)]是列表,不是数组

尝试

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