Reader monad for dependency injection

The Reader monad is available in the Scalaz library. The way dependency injection works with it is that we make each method return a function wrapped in the Reader monad, for example:

def getAverageAgeOfUsersInClass(className: String) =  Reader((userService: UserService) => userService.getAverageAgeOfUsersInClass(className))

In the preceding code, we only expose getAverageAgeOfUsersInClass(className: String) to the users. Typically, for monads, computation here is built, but nothing is done until the last moment. We can build complex operations, use map, flatMap, and for comprehensions. We defer injecting the dependencies until the last moment, where we can simply call apply on a reader with the actual ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.