Skip to content

Instantly share code, notes, and snippets.

@vaclavsvejcar
Last active February 5, 2016 21:45
Show Gist options
  • Save vaclavsvejcar/2a5135f0a716dfb7cb92 to your computer and use it in GitHub Desktop.
Save vaclavsvejcar/2a5135f0a716dfb7cb92 to your computer and use it in GitHub Desktop.
Dead-simple dependency injection based on Scalaz Reader Monad
import scalaz.Reader
/**
* Trait providing helper methods for handling application-wide dependency injection using the
* ''reader monad'' functional pattern.
*
* @author Vaclav Svejcar (v.svejcar@norcane.cz)
*/
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