Reputation: 5757
I'm not sure if this is a Groovy thing or Java thing, I've seen instances of variable assignment such as:
String myVar = ""
...
(myVar) = someMethod(arg1);
do the parenthesis around myVar
have any function, or is it just for readability?
Upvotes: 3
Views: 128
Reputation: 104
The syntax you have show is a form a destructuring.
Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.:
def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo'
You can provide types as part of the declaration if you wish:
def (int i, String j) = [10, 'foo'] assert i == 10 && j == 'foo'
As well as used when declaring variables it also applies to existing variables:
def nums = [1, 3, 5] def a, b, c (a, b, c) = nums assert a == 1 && b == 3 && c == 5
The syntax works for arrays as well as lists, as well as methods that return either of these:
def (_, month, year) = "18th June 2009".split() assert "In $month of $year" == 'In June of 2009'
It's important to note that destructuring still occurs if you only are assigning one variable within parentheses. It takes the first value from the object being destructured.
def (a) = [2, 4, 5]
assert a == 2
The following will throw an exception because there is nothing to destructure
def (a) = 2
This syntax currently has no meaning, but is legal
Upvotes: 4
Reputation: 3346
It's a "thing" in both a Java and Groovy (as in, it's allowed). Groovy can use that syntax for compound assignment (even though it's only assigning one thing...)
String x, y, z
(x, y, z) = ["1", "2", "3"]
Java doesn't have compound assignment, though. Regardless, the Java Language Specifications 15.26.1 states that you can use any number of pairs of parentheses:
If the left-hand operand expression is a field access expression e.f (§15.11), possibly enclosed in one or more pairs of parentheses, then:
All that matters is that when it's completely evaluated, it's a "field access expression" (or an "an array access expression").
do the parenthesis around myVar have any function
Nope.
or is it just for readability?
I'd argue it hurts readability. Consistency in style matters more, though. Maybe they wanted normal assignments to be consistent between compound assignments?
String a
(a) = "123"
String x, y, z
(x, y, z) = ["1", "2", "3"]
Upvotes: 3