对于如果守卫的理解

ang*_*okh 4 monads scala either for-comprehension

如果有警卫,我如何用于理解?

  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")
    }
  }
Run Code Online (Sandbox Code Playgroud)

使用它时出现此错误.

'withFilter' method does not yet exist on scala.util.Either.RightProjection[Error,Success], using `filter' method instead
Run Code Online (Sandbox Code Playgroud)

编辑: 我有另一个错误.我认为如果使用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)
Run Code Online (Sandbox Code Playgroud)

EDIT2

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")
  } 
)
Run Code Online (Sandbox Code Playgroud)

cmb*_*ter 7

我相信你所看到的是编译器警告而不是实际错误.在RightProjection不支持withFilter这是监护条件什么是"首选"(但尚未要求),因此普通的老filter来代替.至于这些功能的区别及其产生的原因,请查看下面的链接以获得解释.

http://scala-programming-language.1934581.n4.nabble.com/Rethinking-filter-td2009215.html#a2009218