Skip to content

Instantly share code, notes, and snippets.

@tomasherman
Created June 13, 2011 17:49
Show Gist options
  • Save tomasherman/1023297 to your computer and use it in GitHub Desktop.
Save tomasherman/1023297 to your computer and use it in GitHub Desktop.
Scala structural type dependency injection between modules
// This file is assumed to be in the API module
// =======================
// service interfaces
trait OnOffDevice {
def on: Unit
def off: Unit
}
trait SensorDevice {
def isCoffeePresent: Boolean
}
// =======================
// service implementations
class Heater extends OnOffDevice {
def on = println("heater.on")
def off = println("heater.off")
}
class PotSensor extends SensorDevice {
def isCoffeePresent = true
}
// =======================
// service declaring two dependencies that it wants injected,
// is using structural typing to declare its dependencies
class Warmer(env: {
val potSensor: SensorDevice
val heater: OnOffDevice
}) {
def trigger = {
if (env.potSensor.isCoffeePresent) env.heater.on
else env.heater.off
}
}
trait Config {
lazy val potSensor:SensorDevice
lazy val heater:OnOfDevice
lazy val warmer:Warmer
}
//for simplicity there is no error handling
object CodecRepository {
var config:Config = null
}
//This file is assumed to be in the server module
class ConfigImpl extends Config {
lazy val potSensor = new PotSensor
lazy val heater = new Heater
lazy val warmer = new Warmer(this) // this is where injection happens
}
CodecConfig.config = new ConfigImpl
// following part can be in plugin as well
class Client(env : { val warmer: Warmer }) {
env.warmer.trigger
}
new Client(CodecConfig.config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment