15 Apr 2004 13:27
Re: New map helper method
On 15 Apr 2004, at 12:15, John Wilson wrote: > On 15 Apr 2004, at 11:57, jastrachan@... wrote: >> I've added a new helper method to Map called get(key, default) which >> takes a default value which is added to the map if the key does not >> already exist. >> >> So you can swap code like this >> >> classmethods = classmap.classmethods; >> if (classmethods == null) { >> classmethods = []; >> classmap.classmethods = classmethods; >> } >> classmethods.add(method); >> >> with >> >> classmap.get("classmethods", []).add(method) >> >> the nice thing about this approach is it works for any type of entry, >> be it a list, map, bean, whatever. The downside is it creates the >> default value each time the method is called. >> > > convenient! > > If there was a version which took a closure we could avoid the > generation of unnecessary objects: > > default = {[]} > > for (i in 0..1000000){ > classmap.get("classmethods", default).add(method) > } > > so the closure only gets called when the default value is needed I had the same initial thought, but then I thought, creating a closure is about the same cost as creating a new list or map etc. Though I guess you could reuse the same closure across various navigations. Maybe we can have an implementation which takes a closure - though I wondered if we'd ever want to use a closure as the value in the map. So we might need 2 methods. c = map.get("valueIsAClosure", someClosure) or use a closure to create the default value value = map.getWith("valueCreatedByClosure", factoryClosure) So this complexity put me off the idea for the moment. James ------- http://radio.weblogs.com/0112098/
RSS Feed