How to avoid dependency injection in Scala?

前端 未结 4 1899
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-10 06:34

I read Dependency Injection Without the Gymnastics PDF which indicates there\'s no need for any fancy DI framework, but it\'s beyond my grasp (at least without concrete examples

4条回答
  •  余生分开走
    2021-02-10 07:25

    Implicit parameters are completely sufficient for the use case you're describing.

    case class A(implicit b: B, c: C)
    case class B(implicit d: D)
    case class C(implicit d: D)
    class D { /* ... */ }
    
    implicit val theD = new D
    implicit val theB = B()
    implicit val theC = C()
    

    Now you can ask for an A just by:

    val a = A()
    

提交回复
热议问题