4

如何使用 if guard 进行推导?

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

2 回答 2

7

我相信您看到的是编译器警告,而不是实际错误。RightProjection不支持withFilter哪个是守卫条件的“首选”(但还不是必需的),所以使用plain old代替filter。至于这些功能的区别以及为什么会这样,请查看下面的链接以获得解释。

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

于 2013-09-23T12:17:25.743 回答
0

在 .之前添加分号或新行if

于 2013-09-23T10:04:12.327 回答