Skip to content

Instantly share code, notes, and snippets.

@js1972
Forked from rintcius/di-value-injection-warmer
Created January 5, 2014 05:42

Revisions

  1. js1972 revised this gist Mar 8, 2014. No changes.
  2. @rintcius rintcius revised this gist Jan 15, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion di-value-injection-warmer
    Original file line number Diff line number Diff line change
    @@ -35,7 +35,7 @@
    // instantiate the services in a configuration module
    object Context {
    // this is where injection happens
    lazy val warmer = new Warmer {
    val warmer = new Warmer {
    val potSensor = new PotSensor
    val heater = new Heater
    }
  3. @rintcius rintcius created this gist Jan 15, 2013.
    44 changes: 44 additions & 0 deletions di-value-injection-warmer
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    // =======================
    // 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
    lazy val warmer = new Warmer {
    val potSensor = new PotSensor
    val heater = new Heater
    }
    }

    Context.warmer.trigger