Using Reader Monad for Dependency Injection

自古美人都是妖i 提交于 2019-12-02 16:42:24

The "reader monad" is just Function1, so all you need to do is accept an argument containing all the things you need. For example:

trait Config {
   def fly: FlyBehaviour
   def quack: QuackBehaviour
}

type Env[A] = Config => A

Now if you want to construct a Duck based on this environment:

val a: Env[Animal] = c => new Duck(c.fly, c.quack)

And then constructing a Zoo based on that is easy:

val z: Env[Zoo] = a andThen (new Zoo(_))

Using Scalaz (or with a bit of work on your own) you can make use of some syntax niceties to "ask" for the config c:

val z: Env[Zoo] = for {
  c <- ask
} yield new Zoo(Duck(c.fly, c.quack))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!