Nothing wrong with it, but wouldn't it be nice to be able to chain those calls and avoid declaring that local variable?
I am currently reading "The Joy of Clojure" and came across the doto macro in clojure, which enables you to do the above like so:
(doto (new java.util.HashMap) ; or just (java.util.HashMap.)
(.put 1 "One")
(.put 2 "Two"))
Nice! But alas, I am forced to use Java by day so I tried to figure out the best approach to do this. The first one comes to mind is this:
new HashMap<Integer, String>(){{
put(1, "one");
put(2, "Two");
}};
Which works perfectly except that it assumes you are the one constructing the object. So I tried a more functional approach:
I believe I've gone and made it worse :(
I also tried a js implementation, which is pretty redundant for maps/objects as object literals are built in:
I would love to see some alternate solutions/improvements or maybe event implementations in other languages!
No comments:
Post a Comment