Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [:] mean in groovy?

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

def foo=[:]

What does it mean?

like image 696
das Keks Avatar asked Apr 04 '14 14:04

das Keks


People also ask

What does ?: Means in Groovy?

Just to add some more insight, the "?:" operator is known as the binary operator or commonly referred to as the elvis operator. The following code examples all produce the same results where x evaluates to true according to Groovy Truth // These three code snippets mean the same thing.

What is & symbol in Groovy script?

Groovy offers four bitwise operators: & : bitwise "and" | : bitwise "or" ^ : bitwise "xor" (exclusive "or")

What is def in Groovy script?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

What does question mark do in Groovy?

Asking for help, clarification, or responding to other answers.


3 Answers

[:] is shorthand notation for creating a Map.

You can also add keys and values to it:

def foo = [bar: 'baz']
like image 104
doelleri Avatar answered Sep 26 '22 03:09

doelleri


[:] 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();
like image 39
Sean Reilly Avatar answered Sep 23 '22 03:09

Sean Reilly


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
like image 44
raina77ow Avatar answered Sep 23 '22 03:09

raina77ow