我如何使用ifguard进行理解?

  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")
    }
  }


使用时出现此错误。

'withFilter' method does not yet exist on scala.util.Either.RightProjection[Error,Success], using `filter' method instead


编辑:
我又遇到一个错误。我认为如果使用防护罩,它将返回选项结果。

[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)


编辑2

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")
  }
)

最佳答案

我相信您看到的是编译器警告,而不是实际错误。 RightProjection不支持withFilter,这是保护条件的“首选”(但不是必需的),因此改用普通的filter。关于这些功能的差异以及产生原因的原因,请查看下面的链接以获取解释。

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

09-11 18:31