Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created January 12, 2016 23:21
Show Gist options
  • Save Allan-Gong/59f3f0fa61baba0cb185 to your computer and use it in GitHub Desktop.
Save Allan-Gong/59f3f0fa61baba0cb185 to your computer and use it in GitHub Desktop.
Dependency Injection in Scala
// cake pattern with self-type annotation
// =======================
// service interfaces
trait OnOffDeviceComponent {
val onOff: OnOffDevice
trait OnOffDevice {
def on: Unit
def off: Unit
}
}
trait SensorDeviceComponent {
val sensor: SensorDevice
trait SensorDevice {
def isCoffeePresent: Boolean
}
}
// =======================
// service implementations
trait OnOffDeviceComponentImpl extends OnOffDeviceComponent {
class Heater extends OnOffDevice {
def on = println("heater.on")
def off = println("heater.off")
}
}
trait SensorDeviceComponentImpl extends SensorDeviceComponent {
class PotSensor extends SensorDevice {
def isCoffeePresent = true
}
}
// =======================
// service declaring two dependencies that it wants injected
trait WarmerComponentImpl {
this: SensorDeviceComponent with OnOffDeviceComponent =>
class Warmer {
def trigger = {
if (sensor.isCoffeePresent) onOff.on
else onOff.off
}
}
}
// =======================
// instantiate the services in a module
object ComponentRegistry extends
OnOffDeviceComponentImpl with
SensorDeviceComponentImpl with
WarmerComponentImpl {
val onOff = new Heater
val sensor = new PotSensor
val warmer = new Warmer
}
// =======================
val warmer = ComponentRegistry.warmer
warmer.trigger
// Using structural typing
// With implicit declarations
// Using Google Guice
// Reader Monad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment