Search code examples
scaladependency-injectioncake-pattern

Is scala's cake pattern possible with parametrized components?


Parametrized components work well with the cake pattern as long as you are only interested in a unique component for each typed component's, example:

trait AComponent[T] {
  val a:A[T]

  class A[T](implicit mf:Manifest[T]) {
    println(mf)
  }
}

class App extends AComponent[Int] {
  val a = new A[Int]()
}

new App

Now my application requires me to inject an A[Int] and an A[String], obviously scala's type system doesn't allow me to extends AComponent twice. What is the common practice in this situation ?


Solution

  • I think the AComponent doesn't need to be parameterized itself. So loose the type parameter and change this into

    trait AComponent {
        val aInt: A[Int]
        val aStr: A[String]
        class A[T](implicit mf:Manifest[T]) {
            println(mf)
        }
    } 
    
    class App extends AComponent {
        val aInt = new A[Int]()
        val aStr = new A[String]()
    }
    

    if you want to be able to provide instances for Int and String