gpt4 book ai didi

scala - 用于理解 if 守卫

转载 作者:行者123 更新时间:2023-12-04 23:54:18 28 4
gpt4 key购买 nike

我如何使用 if 守卫的理解?

  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这是 guard 条件的“首选”(但还不是必需的),所以很简单filter改为使用。至于这些功能的区别以及为什么会出现这种情况,请查看下面的链接以获取解释。

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

关于scala - 用于理解 if 守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18954808/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com