What does [:] mean in groovy?

霸气de小男生 提交于 2020-07-03 01:45:41

问题


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

def foo=[:]

What does it mean?


回答1:


[:] is shorthand notation for creating a Map.

You can also add keys and values to it:

def foo = [bar: 'baz']



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/22865107/what-does-mean-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!