I'm reading this great article about dependency injection in scala with Reader monad.
The original example is working well, but I did a little bit change on the return types of the UserRepository.get/find
. It was User
, but I changed it to Try[User]
.
Then the code won't be compiled, I had tries many times, but still without lucky.
import scala.util.Try
import scalaz.Reader
case class User(email: String, supervisorId: Int, firstName: String, lastName: String)
trait UserRepository {
def get(id: Int): Try[User]
def find(username: String): Try[User]
}
trait Users {
def getUser(id: Int) = Reader((userRepository: UserRepository) =>
userRepository.get(id)
)
def findUser(username: String) = Reader((userRepository: UserRepository) =>
userRepository.find(username)
)
}
object UserInfo extends Users {
def userEmail(id: Int) = {
getUser(id) map (ut => ut.map(_.email))
}
def userInfo(username: String) =
for {
userTry <- findUser(username)
user <- userTry // !!!!!!!! compilation error
bossTry <- getUser(user.supervisorId)
boss <- bossTry // !!!!!!!! compilation error
} yield Map(
"fullName" -> s"${user.firstName} ${user.lastName}",
"email" -> s"${user.email}",
"boss" -> s"${boss.firstName} ${boss.lastName}"
)
}
The compilation error is:
Error:(34, 12) type mismatch;
found : scala.util.Try[Nothing]
required: scalaz.Kleisli[scalaz.Id.Id,?,?]
user <- userTry
^
and
Error:(36, 12) type mismatch;
found : scala.util.Try[scala.collection.immutable.Map[String,String]]
required: scalaz.Kleisli[scalaz.Id.Id,?,?]
boss <- bossTry
^
I read the document of Kleisli.flatMap
(The return type of findUser
and getUser
is Kleisli
), it requires the parameter type is:
B => Kleisli[M, A, C]
Since a Try
won't be a Kleisli
, there are such errors.
I'm not sure how to handle it. Can I use scala.util.Try
here? How can I turn it to a KLeisli
type? How can I make this example work?