Last active
February 5, 2016 21:45
-
-
Save vaclavsvejcar/2a5135f0a716dfb7cb92 to your computer and use it in GitHub Desktop.
Dead-simple dependency injection based on Scalaz Reader Monad
This file contains hidden or 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
import scalaz.Reader | |
/** | |
* Trait providing helper methods for handling application-wide dependency injection using the | |
* ''reader monad'' functional pattern. | |
* | |
* @author Vaclav Svejcar ([email protected]) | |
*/ | |
trait Injector { | |
/** | |
* Injects the specified dependency into the given ''reader monad''. | |
* | |
* = Example of use: = | |
* {{{ | |
* def testReader() = Reader((config: Config) => config.getString("foo.bar")) | |
* def withConfig[R] = inject[Config, R](configToInject) _ | |
* val result: String = withConfig(testReader()) | |
* }}} | |
* | |
* = Or using implicit conversion: = | |
* {{{ | |
* def testReader() = Reader((config: Config) => config.getString("foo.bar")) | |
* implicit def withConfig[R]: (Reader[Config, R] => R) = inject[Config, R](configToInject) | |
* val result: String = testReader() | |
* }}} | |
* | |
* @param dependency dependency to be injected into the ''reader monad'' | |
* @param reader ''reader monad'' | |
* @tparam D type of the dependency | |
* @tparam R type of the result | |
* @return result of the ''reader monad'' operation | |
*/ | |
protected def inject[D, R](dependency: D)(reader: Reader[D, R]): R = reader(dependency) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment