Skip to content

Instantly share code, notes, and snippets.

@kiy0taka
Forked from timyates/tree.md
Created April 24, 2012 09:56
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kiy0taka/2478499 to your computer and use it in GitHub Desktop.
Save kiy0taka/2478499 to your computer and use it in GitHub Desktop.
A one-line tree in Groovy

One line Tree in Groovy

The other day, I saw Harold Cooper's One-line tree in Python via autovivication, and wondered if the same thing was possible in Groovy.

The answer is yes! But you need to define the variable tree before you can assign it to the self-referential withDefault closure, hence with Groovy, it's a two-line solution ;-)

Anyway, given:

def tree = { [:].withDefault{ owner.call() } }

We can then do:

users = tree()
users.harold.username = 'hrldcpr'
users.yates.username = 'tim'

And printing this out

println new groovy.json.JsonBuilder( users ).toPrettyString()

gives:

{
    "harold": {
        "username": "hrldcpr"
    },
    "yates": {
        "username": "tim"
    }
}
@antsmartian
Copy link

Wow! This looks brilliant! your always an Groovy guy! ;)

@hrldcpr
Copy link

hrldcpr commented Apr 24, 2012

Nice!

@crazy4groovy
Copy link

Impressive!

@kingnebby
Copy link

super dig

@Hubbitus
Copy link

All already there ;)

def users = new ConfigObject()

Then using the same:

users.harold.username = 'hrldcpr'
users.yates.username = 'tim'

println new groovy.json.JsonBuilder( users ).toPrettyString()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment