42

While reading some groovy code of another developer I encountered the following definition:

def foo=[:]

What does it mean?

3 Answers 3

55

[:] is shorthand notation for creating a Map.

You can also add keys and values to it:

def foo = [bar: 'baz']
1
  • 2
    I imagine multiple entries are separated by a comma? [bar: 'baz', qux: 'quux'] Commented Jul 19, 2017 at 12:50
16

[:] creates an empty Map. The colon is there to distinguish it from [], which creates an empty List.

This groovy code:

def foo = [:]

is roughly equivalent to this java code:

Object foo = new java.util.LinkedHashMap();
2

Quoting the doc:

Notice that [:] is the empty map expression.

... which is the only Map with size() returning 0. ) By itself, it's rarely useful, but you can add values into this Map, of course:

def emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.foo = 5
assert emptyMap.size() == 1
assert emptyMap.foo == 5
1
  • Technically, "is the only Map with size() returning 0" is untrue. There are lots of possible map instances with size 0, and they definitely don't all have reference equality. They will all be "equal", though (assuming they don't get mutated), which is probably what you meant. Commented Apr 7, 2014 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.