I'm trying to figure out how to get traditional constructor-based dependency injection to work with type class patterns.
For example, given
trait MyTypeClass[A] {
def doSomething(a: A): Unit
}
class TypeClasses(prefix: String) {
implicit val stringTC = new MyTypeClass[String] {
def doSomething(a: String) = println(s"$prefix a")
}
implicit val intTc = new MyTypeClass[Int] {
def doSomething(a: Int) = println(s"s$prefix $a")
}
}
class MyLogic {
def doSomething[A](a: A)(implicit myTypeClass: MyTypeClass[A]) = myTypeClass.doSomething(a)
doSomething("Hello world")
}
What would be the best way to get the implicit type class instances inside an instance of TypeClasses into MyLogic?
The only things I've come up with are to either
a) Inject an instance of TypeClasses into MyLogic in the constructor, and then import instanceOfTypeClasses._. However this has the downside that it has to be repeated every class, and subclasses can't inherit the import.
or b) make TypeClasses a trait, prefix a def, and have MyLogic extend TypeClasses and then dependency inject an instance for prefix in the constructor. However this becomes messy as it's allowing the dependencies for TypeClasses to bleed into MyLogic.