Scala: Dependency Injection Using Structural Typing
Scala has a powerful type system that enables different patterns for expressing dependencies compared with languages like Java or C#. Jamie Webb described an interesting approach using structural typing on the Scala User Mailing List (link to post).
Jamie injected a config object defined using a structural type. This has the benefit of clearly defining the dependencies of a class, whilst allowing the same environment object to be shared. Here is an example from Jamie’s post, which describes a coffee warmer with a dependency on a heater and a pot sensor, the code shown is a modified version from a blog post by Jonas BonĂ©r which uses constructor-based dependency injection:
class Warmer(env: { val potSensor: SensorDevice val heater: OnOffDevice }) { def trigger = { if(env.potSensor.isCoffeePresent) env.heater.on else env.heater.off } }
A simple config object can then be defined instantiates the pot sensor, heater and wires up the warmer:
object Config { lazy val potSensor = new PotSensor lazy val heater = new Heater lazy val warmer = new Warmer(this) }
This seems like a nice pattern, it’s quite elegant, type-safe, easy to test and makes the dependencies of a class explicit. There are a couple of other patterns in this area, I’ll make further posts around those.