Fabiano Taioli
Fabiano Taioli

Reputation: 5540

Overloading maps .field notation

In groovy I have extended a LinkedHashMap and overloaded the getAt,PutAt operators:

class Container extends LinkedHashMap<String, Object> {

     def get(String id){ 'my '+id }
     def put(String id, Object value){ super.put(id, 'val:'+value ) }
     def getAt(String id){ get(id) }
     def putAt(String id, Object value){ put(id, value) }

}

Using my class on groovy seems to work good if i directly call the methods or use the [] notation:

 def c = new Container()
 c['x'] = 'y'
 assert c.get('x') == c['x']

but accessing the map using the field notation does not return the right value:

 assert c['x']!=c.x

How I can overload the '.field' notation to call my overloaded methods as the [] notation?

P.S. I have tried with 'propertyMissing' witout success.

Upvotes: 2

Views: 160

Answers (2)

Will
Will

Reputation: 14539

It works with getProperty and setProperty:

class Container extends LinkedHashMap<String, Object> {
     def getProperty(String id) { 'get prop '+id }
     void setProperty(String id, Object value){ super.put(id, 'val:'+value ) }
}

def c = new Container()
c['x'] = 'y'
assert c.y == 'get prop y'
assert c['x'] == c.x

Upvotes: 2

Opal
Opal

Reputation: 84844

You should have override get() method appropriately:

 def get(String id) { 
     super.get(id) 
 }

Then, it all works fine:

class Container extends LinkedHashMap<String, Object> {

     def get(String id) { 
         super.get(id) 
     }
     def put(String id, Object value) { 
         super.put(id, 'val:'+value ) 
     }
     def getAt(String id) { 
         get(id) 
     }
     def putAt(String id, Object value) { 
         put(id, value) 
     }
}

def c = new Container()
c['x'] = 'y'
assert c.get('x') == c['x']
assert c['x'] == c.x

Upvotes: 0

Related Questions