Dec. 9th, 2010
duck-typing applied to monads
Dec. 9th, 2010 02:31 pmobject closable { type Closable = { def close } class Autoclose[A <: Closable](c: A){ def foreach(f: A => Unit) = { try { f(c) }finally { c.close } } } implicit def autoClosable[A <: Closable](c: A) = new Autoclose(c) //... case class Connection(name:String) { def close = println("closing " + this) } case class Statement(c: Connection,q :String){ def close = println("closing " + this) def exec = println("executing " + q + " on " + c) } def test = for(c <- Connection("conn"); st <- Statement(c,"select * from table")){ st.exec } }
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
(src 10x Ramzi ben Yahia).
... and/or strategies.
I was pondering where do I stick my two factory strategies, or rather strategy factories - wrote an abstract class and thought about having two final static members, with well-named implementations, when it occurred to me - kaboom, it's an enum:
Sure it is obvious. But if it is, why people hardly ever do it this way?
I was pondering where do I stick my two factory strategies, or rather strategy factories - wrote an abstract class and thought about having two final static members, with well-named implementations, when it occurred to me - kaboom, it's an enum:
enum GadgetFactory { christmasGadget { Gadget build(User user, WeakReference<Something>) { ... }, newYearGadget { Gadget build(User user, WeakReference<Something>) { ... }; abstract Gadget build(User user, WeakReference<Something>); }
Sure it is obvious. But if it is, why people hardly ever do it this way?