我正在读这篇关于dependency injection in scala with Reader monad的精彩文章。
原始示例运行良好,但我对UserRepository.get/find
的返回类型做了一些改动。它是User
,但我将其更改为Try[User]
。
然后代码将不会编译,我尝试了很多次,但仍然没有幸运。
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}"
)
}
编译错误是:
Error:(34, 12) type mismatch;
found : scala.util.Try[Nothing]
required: scalaz.Kleisli[scalaz.Id.Id,?,?]
user <- userTry
^
和
Error:(36, 12) type mismatch;
found : scala.util.Try[scala.collection.immutable.Map[String,String]]
required: scalaz.Kleisli[scalaz.Id.Id,?,?]
boss <- bossTry
^
我阅读了Kleisli.flatMap
的文档(返回类型为findUser
且getUser
为Kleisli
),它要求参数类型为:
B => Kleisli[M, A, C]
由于Try
不是Kleisli
,因此存在此类错误。
我不确定如何处理它。我可以在这里使用scala.util.Try
吗?如何将其转换为KLeisli
类型?我怎样才能使这个例子有效?
答案 0 :(得分:20)
你可以使用ReaderT
monad变换器将Reader
monad和Try
monad组成一个monad,你可以使用for
- 理解等等
ReaderT
只是Kleisli
的类型别名,您可以使用Kleisli.kleisli
代替Reader.apply
来构建Reader
- y计算。请注意,Try
的monad实例需要scalaz-contrib
(或者您可以编写自己的实例 - 它非常简单。)
import scala.util.Try
import scalaz._, Scalaz._
import scalaz.contrib.std.utilTry._
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): ReaderT[Try, UserRepository, User] =
Kleisli.kleisli(_.get(id))
def findUser(username: String): ReaderT[Try, UserRepository, User] =
Kleisli.kleisli(_.find(username))
}
现在已经完成了,UserInfo
更加简单(现在也可以编译!):
object UserInfo extends Users {
def userEmail(id: Int) = getUser(id).map(_.email)
def userInfo(
username: String
): ReaderT[Try, UserRepository, Map[String, String]] =
for {
user <- findUser(username)
boss <- getUser(user.supervisorId)
} yield Map(
"fullName" -> s"${user.firstName} ${user.lastName}",
"email" -> s"${user.email}",
"boss" -> s"${boss.firstName} ${boss.lastName}"
)
}
我们可以证明它有效:
import scala.util.{ Failure, Success }
val repo = new UserRepository {
val bar = User("bar@mcfoo.com", 0, "Bar", "McFoo")
val foo = User("foo@mcbar.com", 0, "Foo", "McBar")
def get(id: Int) = id match {
case 0 => Success(bar)
case 1 => Success(foo)
case i => Failure(new Exception(s"No user with id $i"))
}
def find(username: String) = username match {
case "bar" => Success(bar)
case "foo" => Success(foo)
case other => Failure(new Exception(s"No user with name $other"))
}
}
然后:
UserInfo.userInfo("foo").run(repo).foreach(println)
Map(fullName -> Foo McBar, email -> foo@mcbar.com, boss -> Bar McFoo)
与运行Reader
的方式完全相同,但最后会得到Try
。