Skip to content

Instantly share code, notes, and snippets.

@rintcius
Last active December 11, 2015 03:29
Show Gist options
  • Save rintcius/4538061 to your computer and use it in GitHub Desktop.
Save rintcius/4538061 to your computer and use it in GitHub Desktop.
This is the warmer example using value injection on traits. See http://blog.rintcius.nl/post/di-on-steroids-with-scala-value-injection-on-traits.html
// =======================
// 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 value injection to declare its dependencies
trait Warmer {
val potSensor: SensorDevice
val heater: OnOffDevice
def trigger = {
if (potSensor.isCoffeePresent) heater.on
else heater.off
}
}
// =======================
// instantiate the services in a configuration module
object Context {
// this is where injection happens
val warmer = new Warmer {
val potSensor = new PotSensor
val heater = new Heater
}
}
Context.warmer.trigger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment