2013-06-04 27 views
0

以下代碼中的函數f只是試圖打印出它的參數以及它接收的數量。但是,它擴展了陣列參數(但不是陣列列表),如行f(x) // 3所示。反正有f不能擴展數組參數,或者至少檢測到它已經發生,並且可能正確。原因是因爲我的「真正的」f函數並不是微不足道的,而是將它的參數傳遞給給定的函數g,它通常不是一個可變參數函數,而是直接將數組視爲一個參數,而擴展由f堵了起來。Groovy:檢測何時通過陣列

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 

回答

3

我懷疑是否有任何干淨的解決方案,因爲它的行爲像Java可變參數。如果你發表意見concat(Object obj)方法

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(); } 
} 

,所有三種方法將匹配concat(Object... args):您可以測試數組的大小瓶蓋內,或者像在Java中使用方法重載。

0

您可以使用標籤參數如下:

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 

那麼輸出是:

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 
+0

這不正是一個「標籤」,它是一個地圖:-) – Will

+0

是的,但是你真正在做的是命名你的論點。是的,Groovy會製作出他們的地圖。 – vladtax