554374 (1) [Avatar] Offline
#1
Chapter 3 section 3.3.6 talks about using the Reader as a method for injecting a repository into a service:
case class Reader[R, A](run: R => A) {
	def map[B] ...
	def flatMap[B](f: A => Reader[R, B]): Reader[R, B] = 
		Reader(r => f(run(r)).run(r))
}


First off, I can't understand how the flatMap method works in this case. Can someone explain that to me?

Also, while I understand the advantages of this pattern in injecting the repository at the end of a call, it is posited as a better alternative to supplying the repository as part of the method signature for each function in a Service. Well, that is better, but why go that route as opposed to injecting the repository as a field when the Service is instantiated? This would be similar to something you would see in a Spring Service, for example:

class AccountService {
	@Autowired AccountRepository accountRepository; //Injected as needed depending on the context
	public Option<Account> open(String acctNo, String name, ...) {
		accountRepository.open(...);
	}

}