Groovy:检测何时传递数组 [英] Groovy: Detecting when being passed arrays

查看:181
本文介绍了Groovy:检测何时传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中的函数 f 只是试图打印出它的参数以及它接收的数量。但是,它会扩展数组参数(但不是数组列表),如 f(x)// 3 所示。无论如何,让 f 不能扩展数组参数,或者至少检测到它已经发生,并且可能正确。原因是因为我的真正的f函数并不是微不足道的,而是将它的参数传递给给定函数 g ,这通常不是一个可变参数函数而是直接将一个数组作为参数,而由 f 的扩展将这个数据分散。

  def f = {
Object ... args - >
打印有:;
print args.size();
println参数,它们是:;
args.each {println it};
printlnDONE
}

def x = new int [2];
x [0] = 1;
x [1] = 2;

f(1,2); // 1
f([1,2]); // 2
f(x); // 3


解决方案

我怀疑是否有任何干净的解决方案这一点,因为它表现得像Java可变参数。你可以在闭包中测试数组的大小,或者像在Java中一样使用方法重载:

  public class Arraying {
public static void main(String [] args){
//打印2
System.out.println(concat(new Object [] {a,b }));

//打印a。注释第二个concat(),打印1
System.out.println(concat(a));

//打印3
System.out.println(concat(a,b,c));


static String concat(Object ... args){
return String.valueOf(args.length);
}

static String concat(Object obj){return obj.toString();如果您评论 concat(Object obj) 方法,所有三种方法都会匹配 concat(Object ... args)


The function f in the following code simply attempts to print out it's arguments and how many it receives. However, it expands array parameters (but not arraylists) as illustrated on the line f(x) // 3. Is there anyway to get f not to expand array parameters, or alternatively at the very least detect that it has happened, and perhaps correct for it. The reason for this is because my "real" f function isn't as trivial and instead passes it's parameters to a given function g, which often isn't a variable parameter function which instead expects an array directly as an argument, and the expansion by f mucks that up.

def f = { 
  Object... args -> 
    print "There are: "; 
    print args.size(); 
    println " arguments and they are: "; 
    args.each { println it }; 
    println "DONE" 
}

def x = new int[2];
x[0] = 1;
x[1] = 2;

f(1,2); // 1
f([1,2]); // 2
f(x); // 3

解决方案

I doubt there is any clean solution to this, as it behaves as Java varargs. You may test the size of the array inside the closure, or, as in Java, use a method overload:

public class Arraying {
  public static void main(String[] args) {
    // prints "2"
    System.out.println( concat( new Object[] { "a", "b" } ) ); 

    // prints "a". Commenting the second concat(), prints "1"
    System.out.println( concat( "a" ) ); 

    // prints "3"
    System.out.println( concat( "a", "b", "c" ) ); 
  }

  static String concat(Object... args) {
    return String.valueOf(args.length);
  }

  static String concat(Object obj) { return obj.toString(); }
}

If you comment the concat(Object obj) method, all three methods will match the concat(Object... args).

这篇关于Groovy:检测何时传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆