Contact Us

Use the form on the right to contact us.


123 Street Avenue, City Town, 99999

(123) 555-6789


You can set your address, phone number, email and site description in the settings tab.
Link to read me page with more information.


Scala: Dependency Injection Using Structural Typing

Mark Thomas

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 = {

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.