Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: GROOVY-6516

...

Code Block
languagegroovy
def map4= [:]
map4[ 1 ]= 'a'
map4[ 2 ]= 'b'
map4[ true ]= 'p' //we can use boolean values as a key
map4[ false ]= 'q'
map4[ null ]= 'x' //we can also use null as a key
map4[ 'null' ]= 'z'
assert map4 == [1:'a', 2:'b', (true):'p', (false):'q', (null):'x', 'null':'z' ]

We can also use the '+' and '<<' operators to add elements to the map. Note that '<<' produces modifies the map while '+=' creates a new map:

Code Block
languagegroovy
def map4a = [:]
def map5a = map4a
assert map5a.is(map4a)
map4a << ['b':'b value']
assert map5a.is(map4a)
map4a+= ['a':'a value'] // map4a is not the original map4a anymore
assert !map5a.is(map4a)
assert map4a == [b:'b value', a:'a value']
assert map5a == [b:'b value']

To use the value of a String as the key value of a map, simply surround the variable with parenthesis. 

...

Code Block
languagegroovy
import java.beans.*
def map = new ObservableMap({!(it instanceof Closure)})
map.addPropertyChangeListener({ evt ->
   println "${evt.propertyName}: ${evt.oldValue} -> ${evt.newValue}"
} as PropertyChangeListener)
def bean = new Expando( map )
bean.lang = 'Groovy'  // prints lang: null -> Groovy
bean.sayHello = { name -> "Hello ${name}" } // prints nothing, event is skipped
assert 'Groovy' == bean.lang
assert 'Hello Groovy' == bean.sayHello(bean.lang)

Infinite nested maps tip

With the help of withDefault we can easily create inifinite nested maps structure :

Code Block
languagegroovy
Map infiniteNestedMaps = { [:].withDefault{ owner.call() } }()
        
infiniteNestedMaps.a.b.c.d.e.f.g = 42
        
assert infiniteNestedMaps.a.b.c.d.e.f.g == 42