Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
You can’t perform that action at this time.