Search code examples
groovyobservableobservers

How can I access the original map after wrapping it with ObservableMap?


I've created a map and then wrapped it as an ObservableMap. Later on, I try to access the original, unwrapped map, but I can't seem to access it. It seems to come back null.

private def _swarms = [:]
private def swarms = new ObservableMap(_swarms)
...
def orig = swarms.content        // returns null
orig = swarms.mapDelegate        // returns null

I don't see anything else at http://groovy.codehaus.org/api/groovy/util/ObservableMap.html that looks promising.


Solution

  • We cannot refer the property as a field in case of a Map interface. It will try to look for a key with that name and would return null if key<->value pair is absent. Try this instead:

    def _swarms = [ a : 1 ]
    def swarms = new ObservableMap( _swarms )
    
    assert swarms.getContent() == [ a : 1 ]
    assert swarms.getMapDelegate() == [ a : 1 ]
    
    // Similar anomaly
    assert !swarms.class
    assert swarms.getClass().simpleName == "ObservableMap"
    

    Similarly, you cannot use .class on Map. Instead getClass() has to be used.