Scala 用于理解if-guard
如何使用if-guard进行理解Scala 用于理解if-guard,scala,monads,for-comprehension,either,Scala,Monads,For Comprehension,Either,如何使用if-guard进行理解 type Error = String type Success = String def csrfValidation(session:Session, body:JsValue):Either[Error,Success] = { val csrfRet = for (csrfSession <- csrfStateSessionValidation(session).right;
type Error = String
type Success = String
def csrfValidation(session:Session, body:JsValue):Either[Error,Success] = {
val csrfRet = for (csrfSession <- csrfStateSessionValidation(session).right;
csrfReq <- csrfStateReqBodyValidation(body).right if (csrfSession == csrfReq)) yield (csrfReq)
if (csrfRet.isRight)
Right(csrfRet)
else {
Logger.warn("request and session csrf is not the same")
Left("Oops,something went wrong, request and session csrf is not the same")
}
}
编辑:
我又犯了一个错误。我认为如果使用了guard,它会返回一个选项结果
[error] type mismatch;
[error] found : Option[scala.util.Either[Nothing,controllers.ProfileApiV1.Success]]
[error] required: scala.util.Either[?,?]
[error] csrfReq <- csrfStateReqBodyValidation(body).right if (csrfSession == csrfReq)) yield (csrfReq)
[error]类型不匹配;
找到[错误]:选项[scala.util.Nothing,controllers.ProfileApiV1.Success]]
[错误]必需:scala.util.或[?,?]
[错误]csrfReq
如果(x==y)右(x)
左上角(“值不同”)
}
)
在if
前面添加分号或新行 我相信您看到的是编译器警告,而不是实际错误。RightProjection
不支持withFilter
,这是防护条件的“首选”(但不是必需的),因此改用普通的旧过滤器。至于这些功能的区别以及为什么会出现这种情况,请查看下面的链接以获得解释
2.10。我遗漏了什么吗?有没有办法抑制这个警告?我检查过它在我使用过的地方是无害的,但在每一次构建中都会出现。
[error] type mismatch;
[error] found : Option[scala.util.Either[Nothing,controllers.ProfileApiV1.Success]]
[error] required: scala.util.Either[?,?]
[error] csrfReq <- csrfStateReqBodyValidation(body).right if (csrfSession == csrfReq)) yield (csrfReq)
This is what I did to fix above error. I also move if-guard to later process.
val result = for {
foo <- Right[String,String]("teststring").right
bar <- Right[String,String]("teststring").right
} yield (foo, bar)
result fold (
ex => Left("Operation failed with " + ex),
v => v match {
case (x,y) =>
if (x == y) Right(x)
else Left("value is different")
}
)