Domanda

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

def foo=[:]

What does it mean?

È stato utile?

Soluzione

[:] is shorthand notation for creating a Map.

You can also add keys and values to it:

def foo = [bar: 'baz']

Altri suggerimenti

[:] 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();

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top