How to avoid dependency injection in Scala?

前端 未结 4 1886
爱一瞬间的悲伤
爱一瞬间的悲伤 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:05

    You may solve it with self-types.

    A depends on both B and C and both B and C depend on D

    so one could write this like that:

    class A {
      self: B with C => 
    }
    
    trait B { 
      self: D => 
    }
    
    trait C {
      self: D => 
    }
    
    trait D {}
    

    and then on a call side:

    val x = new A with BImpl with CImpl with DImpl
    

    but code below won't compile, because dependencies on B,C,D classes not resolved:

    val x = new A
    

提交回复
热议问题