Не знаю, относится ли это к Groovy или Java, но мне встречались такие присваивания:
String savedText = ""
...
(savedText) = readText(setting);
скобки вокруг savedText что-нибудь делают или лишь должны улучшать читаемость?
Не знаю, относится ли это к Groovy или Java, но мне встречались такие присваивания:
String savedText = ""
...
(savedText) = readText(setting);
скобки вокруг savedText что-нибудь делают или лишь должны улучшать читаемость?
I don't know whether this belongs to Groovy or Java, but I've come across assignments written like this:
String savedText = ""
...
(savedText) = readText(setting);
do parentheses enclosing savedText do anything, or are they only meant to improve readability?
И Java, и Groovy допускают такую "штуку" (то есть синтаксис корректен). В Groovy эта запись поддерживает составное присваивание (хотя здесь присваивается только один элемент...)
String left, middle, right
(left, middle, right) = ["4", "5", "6"]
В Java составного присваивания, однако, нет. Но Java Language Specifications 15.26.1 (https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.26.1) допускает сколько угодно окружающих скобок:
Когда выражение левого операнда является обращением к полю e.f (§15.11), возможно окружённым любым количеством пар скобок, то:
Важно лишь, чтобы после полного вычисления получалось обращение к полю (или элементу массива).
скобки вокруг savedText что-нибудь делают
Нет.
или лишь должны улучшать читаемость?
На мой взгляд, читать становится труднее. Впрочем, единый стиль важнее. Возможно, хотели привести простые присваивания к стилю составных?
String single
(single) = "456"
String left, middle, right
(left, middle, right) = ["4", "5", "6"]
Both Java and Groovy allow this "thing" (that is, the syntax is legal). In Groovy, this syntax supports compound assignment (despite there being just one item here...)
String left, middle, right
(left, middle, right) = ["4", "5", "6"]
Java, however, offers no compound assignment. Still, the Java Language Specifications 15.26.1 (https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.26.1) permits arbitrarily many surrounding parentheses:
When the expression forming the left operand is a field access e.f (§15.11), optionally surrounded by any number of paired parentheses, then:
What counts is whether full evaluation yields an access to a field (or to an array element).
do parentheses enclosing savedText do anything
No.
or are they only meant to improve readability?
To me it reduces readability. A consistent style is more important, however. Perhaps the intention was matching simple assignments to the style of compound assignments?
String single
(single) = "456"
String left, middle, right
(left, middle, right) = ["4", "5", "6"]
Groovy
Показанный синтаксис представляет собой разновидность деструктуризации.
1.2.1. Multiple assignment (https://groovy-lang.org/semantics.html#_multiple_assignment)
В Groovy есть множественное присваивание, позволяющее нескольким переменным получать значения одновременно, например:
def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo'При желании в объявлении можно указать типы:
def (int i, String j) = [10, 'foo'] assert i == 10 && j == 'foo'Это работает не только при объявлении, но и с переменными, объявленными ранее:
def nums = [1, 3, 5] def a, b, c (a, b, c) = nums assert a == 1 && b == 3 && c == 5Синтаксис подходит и для массивов, и для списков, и для методов, возвращающих любой из этих вариантов:
def (_, month, year) = "18th June 2009".split() assert "In $month of $year" == 'In June of 2009'
Помните, что деструктуризация происходит даже тогда, когда внутри скобок только одна переменная для присваивания. Ей достаётся первый элемент деструктурируемого значения.
def (slot) = [3, 6, 7]
assert slot == 3
Следующий пример выбрасывает исключение, поскольку деструктурировать здесь нечего
def (slot) = 3
Java
Сейчас это допустимая запись без особого смысла
Groovy
The displayed syntax is a kind of destructuring operation.
1.2.1. Multiple assignment (https://groovy-lang.org/semantics.html#_multiple_assignment)
Multiple assignment is available in Groovy, allowing several variables to receive their values together, for instance:
def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo'Types may also appear within the declaration, if desired:
def (int i, String j) = [10, 'foo'] assert i == 10 && j == 'foo'This works not only for variable declarations but also for variables declared earlier:
def nums = [1, 3, 5] def a, b, c (a, b, c) = nums assert a == 1 && b == 3 && c == 5Arrays work with this syntax too, along with lists and methods returning either kind:
def (_, month, year) = "18th June 2009".split() assert "In $month of $year" == 'In June of 2009'
Remember that destructuring happens even when the parentheses contain just a single variable for assignment. The assigned result is the initial element of the value being destructured.
def (slot) = [3, 6, 7]
assert slot == 3
This next example raises an exception, as no destructuring can be performed
def (slot) = 3
Java
At present this is legal syntax without any particular meaning
Вот объявление enum, которое я использую в GDScript: Хочу случайно выбирать вариант enum, не перечисляя все возможные вариант…
Как в Nim записать операцию взятия остатка? cell % 7 == 0 выдаёт undeclared identifier: '%' Ни поиск в Google, ни просмотр SO…
Как сделать так, чтобы моя функция возвращала значение после завершения выполнения? Например, у меня есть: ROUTINE N ? N ⍴ 12…