Skip to content

Instantly share code, notes, and snippets.

@ppazos
Forked from timyates/tree.md
Created August 26, 2018 18:15
Show Gist options
  • Save ppazos/544e7ea1382e169448a39311bbf9e02d to your computer and use it in GitHub Desktop.
Save ppazos/544e7ea1382e169448a39311bbf9e02d to your computer and use it in GitHub Desktop.
A two-line tree in Groovy

Two line Tree in Groovy


Update!

Wow... Kiyotaka Oku's fork of this shows how to do it in one line :-)


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
tree = { -> return [:].withDefault{ tree() } }

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"
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment