Created
March 11, 2011 10:18
-
-
Save samueltardieu/865697 to your computer and use it in GitHub Desktop.
Example of Scala injection of a singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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