Groovy: Detecting when being passed arrays

怎甘沉沦 提交于 2019-12-12 04:52:11

问题


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

回答1:


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).




回答2:


You can use a label for the argument as follow:

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(a:x); // <--- used label 'a', or anything else 

then the output is:

There are: 2 arguments and they are: 
1
2
DONE
There are: 1 arguments and they are: 
[1, 2]
DONE
There are: 1 arguments and they are: 
[a:[1, 2]]
DONE


来源:https://stackoverflow.com/questions/16911788/groovy-detecting-when-being-passed-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!