History | Log In     View a printable version of the current page.  
Issue Details (XML | Word | Printable)

Key: GROOVY-158
Type: New Feature New Feature
Status: Closed Closed
Resolution: Fixed
Priority: Major Major
Assignee: Jochen Theodorou
Reporter: james strachan
Votes: 2
Watchers: 1
Operations

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

Multiple assignment

Created: 27/Jan/04 06:46 AM   Updated: 22/Apr/08 06:32 PM
Component/s: GEP
Affects Version/s: None
Fix Version/s: 1.6

Time Tracking:
Not Specified

Issue Links:
Related
 
dependent
 


 Description  « Hide
Support for multiple assignment to simulate multiple return types:

a, b, c = someFunctionReturningAListOfThreeElements()

If more elements are returned than the number of variables to assign values to, we could get the head of list in the first variable and the rest of the list in the second variable:

head, tail = [1,2,3,4]
assert head == 1
assert tail == [2,3,4]

Can also be used for variable swapping
x, y = [y, x]
x, y = y, x

We have to be careful with varibale definitions, because currently:
def a, b, c = someFunctionReturningList()
because currently, a and b would be null, while c would be assigned to the value of the return of the function.

A GEP should be created to present all the possibilities, syntax, edge cases.

Further ideas (subsequent feature enhancements) could be considered like fetching matching groups from regex:
def regex = ~/firstname: (.), name: (.)/
firstname, name = ("firstname: Guillaume, name: Laforge") =~ regex)
assert firstname == "Guillaume"
assert name == "Laforge"



 All   Comments   Work Log   Change History      Sort Order: Ascending order - Click to sort in descending order
james strachan - 16/Feb/04 02:11 AM
We should also expand this to include list indexing for the lvalue. e.g.

list[a, b, c] = someListExpr

would expand to

t = someListExpr
list[a] = t[0]
list[b] = t[1]
list[c] = t[2]


John Stump - 21/Jul/04 11:12 AM
Your initial syntax implies that groovy will never support the comma operator, because if we did there might be a conflict. I personally never use the comma operator in Java except in for() loops, but as I understand it, Groovy will someday support the standard for() loop.

chocolateboy - 26/Jun/05 08:36 PM
The comma operator would also conflict with tuples, which are also planned.

Paul King - 30/Nov/07 09:04 PM - edited

Jochen Theodorou - 22/Apr/08 07:13 AM
since there was low feedback on this the only form that is supported atm is

a,b = [1,2]

meaning no declaration and the number of arguments must match


Paul King - 22/Apr/08 06:32 PM
Just as a comment for future Jira searchers. This does allow Groovy to do the often discussed swap two variables without a temp variable! E.g.:
def a = 1
def b = 2
[a, b] = [b, a]
println a // => 2
println b // => 1