You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Eric Milles (Jira)" <ji...@apache.org> on 2022/11/14 14:56:00 UTC

[jira] [Comment Edited] (GROOVY-10788) Consider adding Object deconstruction a-la Javascript

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

Eric Milles edited comment on GROOVY-10788 at 11/14/22 2:55 PM:
----------------------------------------------------------------

I think "def m = [:a, :b, c:3]" is going to give a better editor experience -- for local variable occurrence highlight/navigate -- and will not conflict with statement label identification.

I did think of a way to multi-assign from a map, in case anyone stumbles on this and wants to do it:
{code:groovy}
def map = [a:1,b:2]
def (a,b) = map.subMap('a','b').values()
{code}

*Update:* if map does not contain "a" or "b" then subMap will not and this trick falls apart.


was (Author: emilles):
I think "def m = [:a, :b, c:3]" is going to give a better editor experience -- for local variable occurrence highlight/navigate -- and will not conflict with statement label identification.

I did think of a way to multi-assign from a map, in case anyone stumbles on this and wants to do it:
{code:groovy}
def map = [a:1,b:2]
def (a,b) = map.subMap('a','b').values()
{code}

> Consider adding Object deconstruction a-la Javascript
> -----------------------------------------------------
>
>                 Key: GROOVY-10788
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10788
>             Project: Groovy
>          Issue Type: Improvement
>            Reporter: Konstantin Smirnov
>            Priority: Major
>         Attachments: image-2022-10-07-07-52-27-123.png
>
>
> In JS you can perform following operations on Arrays:
> {code:java}
> const [ a, b, c ] = [ 1, 2, 3 ]
> {code}
> which corresponds to mutli-assignment in Groovy.
> However JS does some really nice syntactic sugar with Object deconstruction on top:
> {code:javascript}
> // "forward"
> const object = { question:'about life', answer:42, z:11 }
> const { question, answer } = object
> // "backward"
> const newObject = { question, answer }
> {code}
> This way you can save a lot of code-duplication between declaring variables and Map keys.
> The syntax could look like:
> {code:groovy}
> // "forward"
> def object = [ question:'about life', answer:42, z:11 ]
> def ( question, answer ) = object
> // "backward"
> def newObject = [ :question, answer: ]{code}
> What do you think?



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