Groovy:相同的参数,不同的结果 [英] Groovy: same parameters, different results
问题描述
在下面的代码中, x.test()
返回 [1,2]
。
因此 y = [1,2]
。
然而 f([1,2])
打印 1
,但是 f(y)
打印 2
。
如何写 f(y)
,以便打印 1
?
相反, f(z)
打印 1
,即使 z = y
。
def f = {Object .. 。args - > println args.size(); };
class Test {Object [] test(){return [1,2]; }}
def x = new Test();
def y = x.test();
def z = [1,2];
f([1,2]); // 1
f(y); // 2
f(z); // 1
问题在于 y
和 z
虽然看起来相同,但实际上是不同的类型。 y
是一个 Object []
,而 z
是一个的ArrayList<整数>
。 Groovy以不同的方式处理数组和列表,自动将前者强制转换为可变参数列表,但不包括后者。
println y.getClass (); // class [Ljava.lang.Object
println z.getClass(); //类java.util.ArrayList
至于解决问题的方法,可以将 test()
返回一个 List
而不是一个数组:
class Test {List test(){return [1,2]; }}
或者将数组传递给 f :
f(y as List); // 1
In the below code, x.test()
returns [1,2]
.
So y = [1,2]
.
Yet f([1,2])
prints 1
, but f(y)
prints 2
.
How do I write f(y)
so it prints 1
?
Perversely, f(z)
prints 1
, even though z = y
.
def f = { Object... args -> println args.size(); };
class Test { Object[] test() { return [1,2]; } }
def x = new Test();
def y = x.test();
def z = [1,2];
f([1,2]); // 1
f(y); // 2
f(z); // 1
The problem is that y
and z
, while they appear to be the same, are actually of different types. y
is an Object[]
while z
is an ArrayList<Integer>
. Groovy handles arrays and lists differently, automatically coercing the former into a varargs parameter list, but not the latter.
println y.getClass(); // class [Ljava.lang.Object
println z.getClass(); // class java.util.ArrayList
As for a solution to your problem, either change your test()
to return a List
instead of an array:
class Test { List test() { return [1,2]; } }
or manually coerce the array into a list when you pass it to f
:
f(y as List); // 1
这篇关于Groovy:相同的参数,不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!