Skip to content

Instantly share code, notes, and snippets.

@samueltardieu
Created March 11, 2011 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samueltardieu/865697 to your computer and use it in GitHub Desktop.
Save samueltardieu/865697 to your computer and use it in GitHub Desktop.
Example of Scala injection of a singleton
// StopWatch class
abstract class StopWatch {
def giveTime: Time
}
// Class is declared abstract as it is lacking a StopWatch which will be later injected.
// Note that we could have defined a default value here and thus made the class concrete.
abstract class FooBar {
val watch: StopWatch
}
// This is a companion object, equivalent to static methods in Java,
// it is *not* a singleton and does not belong to the FooBar class hierarchy.
object FooBar {
def doSomething ...
}
// This is a singleton -- note that it extends a type and thus is an instance
// of StopWatch.
object AtomicStopWatch extends StopWatch {
override def giveTime = obtainTimeFromAtomicClockAndReturnIt
}
// This injects the dependency into an instance of FooBar
val myAtomicFooBar = new FooBar { override val watch = AtomicStopWatch }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment