2013-09-23 20 views
3

如果警卫有什么用途?用于带警卫的解释

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) 

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

2.10。我错过了什么? – angelokh

回答

7

我相信你看到的是一个编译器警告,而不是一个实际的错误。 RightProjection不支持withFilter这是什么是“首选”(但尚未要求)的保卫条件,所以使用普通的旧filter来代替。至于这些功能的区别以及为什么会出现这种情况,请查看下面的链接以获取解释。

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

+0

有没有办法抑制这个警告?我检查了它在我使用它的地方是无害的,但是在每个版本中都显示出来。 –

+0

@JürgenStrobel,我不确定;还没有尝试过。 – cmbaxter

0

添加或者分号或只是if之前新线。

+0

它没有工作。 – angelokh