Issue Details (XML | Word | Printable)

Key: GROOVY-1803
Type: Bug Bug
Status: Closed Closed
Resolution: Won't Fix
Priority: Major Major
Assignee: Jochen Theodorou
Reporter: John Redford
Votes: 0
Watchers: 1
Operations

If you were logged in you would be able to see more operations.
groovy

Cannot apply function/closure arguments with defaults

Created: 26/Mar/07 10:34 AM   Updated: 02/Jul/07 05:03 AM
Component/s: None
Affects Version/s: 1.0
Fix Version/s: 1.1-beta-2

Time Tracking:
Not Specified

Environment: N/A


 Description  « Hide
The following code demonstrates the problem. It is handy to be able to "apply" arguments to a function/closure, but these calls do not properly handle the presence of default arguments.

def xx = { a, b, c = "default" -> println "a $a b $b c $c"; };
xx(1, 2, 3);
xx([1, 2, 3]);
z = [1, 2, 3];
xx(z);
z = [1, 2];
xx(1, 2);
xx(z);

def yy (a, b, c = "default") { println "a $a b $b c $c"; };
yy(1, 2, 3);
yy([1, 2, 3]);
z = [1, 2, 3];
yy(z);
z = [1, 2];
yy(1, 2);
yy(z);

This would make the following ambiguous:

def zz (a, b = "default", c = "default") { println "a $a b $b c $c"; };
zz([1, 2, 3]);

There needs to be a way, as with Java varargs, to indicate when an array is "an array of arguments" and when it is "an argument that is an array".

The current, Java-like approach may not be the best. It would be nice to have an "apply" method on functions/closures that would explicitly take "an array of arguments", much like Scheme/JavaScript:

def zz (a, b = "default", c = "default") { println "a $a b $b c $c"; };
zz([1, 2, 3]); // "a [1, 2, 3] b default c default"
zz.apply([1,2,3]); // "a 1 b 2 c 3"



 All   Comments   Work Log   Change History      Sort Order: Ascending order - Click to sort in descending order
Jochen Theodorou added a comment - 26/Mar/07 11:17 AM
I agree that if xx(z) is not working, it is a bug, but [1,2,3] is not in general a placeholder for multiple arguments. A List, when given as first and only argument is replaced by its arguments, when the number of list elements fits the number of arguments of the method we want to call. There is a placeholder for saying that an parameter is an array, that is [] like Object[] foo. If that parameter is the alst one, then the logic of variable args can be used here. The current approach with default arguments is not there to simulate vargs. If you want to have vargs then do it like this:

def x={Object[] a -> println a}
x(1,2,3)
x(1,2)

if you ant a list to be forced to be expanded, then you can do this by using the star operator:

zz(*[1,2,3]) // a=1,b=2,c=3

but in case of zz the list is used, because you gave zz a list.

So I make this a bug with a higher priority, because yy([1,2]) is not calling the yy method with two arguments.


Jochen Theodorou added a comment - 02/Jul/07 05:03 AM
I close this as Won't Fix, because the issue I saw is a very different one and will get it's own number. See GROOVY-1963