How do I use for comprehensions with 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")
}
}
I got this error when using it.
'withFilter' method does not yet exist on scala.util.Either.RightProjection[Error,Success], using `filter' method instead
EDIT: I got another error. I think it returns an option result when if guard is used.
[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)
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")
}
)
I believe what you are seeing is a compiler warning and not an actual error. The RightProjection
does not support withFilter
which is what is "preferred" (but not yet required) for a guard condition, so plain old filter
is used instead. As to the difference to these functions and why this came about, check out the link below for an explanation.
http://scala-programming-language.1934581.n4.nabble.com/Rethinking-filter-td2009215.html#a2009218
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With