[ 
https://issues.apache.org/jira/browse/GROOVY-11525?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17904679#comment-17904679
 ] 

Daniel Sun commented on GROOVY-11525:
-------------------------------------

Let's simplify the syntax of expression scope variable in statement while, if 
and switch.

For example,

{code}

// parentheses accept an expression

while (some_expression) \{ ... }

 

// According to the usage of expression scoped variable,

// we could write code like the following.

// Maybe we could allow the variable "c" to be accessed in the body of while, 
if, switch, etc.

while (char c; (c = stream.peek()) != ' ') {

  // can reference "c" here

}

 

while ((char c; (c = stream.peek()) != ' ')) {

  // cannot reference "c" here because of the additional parentheses

}

{code}

> Support expression scope variable
> ---------------------------------
>
>                 Key: GROOVY-11525
>                 URL: https://issues.apache.org/jira/browse/GROOVY-11525
>             Project: Groovy
>          Issue Type: New Feature
>            Reporter: Daniel Sun
>            Priority: Major
>
> Let's take a look at the following code first:
> {code}
> int hash(Object key) {
>    int h;
>    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
> }
> {code}
> variable {{h}} is actually an expression scope variable, but current syntax 
> doesn't support.
> I propose an expression scope variable syntax, e.g. 
> Proposed syntax 1:
> {code}
> // Just support declaring variables of same type
> (int h, x, y; ...)
> {code}
> {code}
> int hash(Object key) {
>    // h is only visible in the expression
>    return (int h; (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16))
> }
> {code}
> We can reduce the scope of {{h}} further:
> {code}
> int hash(Object key) {
>    // h is only visible in the expression
>    return (key == null) ? 0 : (int h; (h = key.hashCode()) ^ (h >>> 16))
> }
> {code}
> Proposed syntax 2(I prefer the syntax):
> {code}
> // Support declaring variables of different types
> (int h, X x, Y y -> ...)
> {code}
> {code}
> int hash(Object key) {
>    // h is only visible in the expression
>    return (int h -> (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16))
> }
> {code}
> {code}
> int hash(Object key) {
>    // h is only visible in the expression
>    return (key == null) ? 0 : (int h -> (h = key.hashCode()) ^ (h >>> 16))
> }
> {code}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to