Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for comprehensions with if guard

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")
  } 
)
like image 573
angelokh Avatar asked Mar 22 '23 07:03

angelokh


1 Answers

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

like image 80
cmbaxter Avatar answered Apr 02 '23 11:04

cmbaxter