可以在理解中使用不同的单子吗?这是使用的代码map
case class Post(id: Int, text: String)
object PostOps {
def find(id: Int) : Option[Post] = if (id == 1) Some(Post(1, "text")) else None
def permitted(post: Post, userId: Int) : Try[Post] = if (userId == 1) Success(post) else Failure(new UnsupportedOperationException)
def edit(id: Int, userId : Int, text: String) = find(id).map(permitted(_, userId).map(_.copy(text = text))) match {
case None => println("Not found")
case Some(Success(p)) => println("Success")
case Some(Failure(_)) => println("Not authorized")
}
}
Run Code Online (Sandbox Code Playgroud)
理解的直接版本由于明显的原因而无法使用,但是是否可以使它与一些其他代码一起使用?我知道在C#中是可能的,所以如果不在Scala中,那会很奇怪。
你只能在 a 中使用一种类型的 monad 来理解,因为它只是flatMapand 的语法糖map。
如果您有一堆 monad(例如Future[Option[A]]),您可以使用 monad 转换器,但这不适用于此处。
针对您的情况的一种解决方案可能是使用一个 monad:从OptiontoTry或从两个Option和Tryto 转到Either[String, A]。
def tryToEither[L, R](t: Try[R])(left: Throwable => L): Either[L, R] =
t.transform(r => Success(Right(r)), th => Success(Left(left(th)))).get
def edit(id: Int, userId: Int, text: String) = {
val updatedPost = for {
p1 <- find(id).toRight("Not found").right
p2 <- tryToEither(permitted(p1, userId))(_ => "Not Authorized").right
} yield p2.copy(text = text)
updatedPost match {
case Left(msg) => println(msg)
case Right(_) => println("success")
}
}
Run Code Online (Sandbox Code Playgroud)
您可以定义错误类型而不是使用String,这样您就可以使用Either[Error, A].
sealed trait Error extends Exception
case class PostNotFound(userId: Int) extends Error
case object NotAuthorized extends Error
Run Code Online (Sandbox Code Playgroud)