How to avoid dependency injection in Scala?

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

    I think @om-nom-nom's answer is quite close to what you want. Here is what I've got:

    class A {
      self: B with C => 
    
      def sum = tripleD + doubleD
    }
    
    trait B { 
      self: D => 
    
      def tripleD = x * 3
    }
    
    trait C {
      self: D => 
    
      def doubleD = x * 2
    }
    
    trait D extends B with C {
      val x: Int
    }
    
    trait E extends D {
      val x = 3
    }
    
    trait F extends D {
      val x = 4
    }
    
    val a = new A with E
    val b = new A with F
    
    println("a.sum = " + a.sum)
    println("b.sum = " + b.sum)
    

提交回复
热议问题