2014-03-25 26 views
4

我有這個實現scalaz驗證,它似乎是隱式scalaz.Bind不在範圍內,因此表達式不工作。 下面是代碼:驗證:隱式scalaz.Bind未找到

import scalaz._ 
import Scalaz._ 

case class User(name: String, knowScala: Boolean, age: Int) 

object PublicValidationSpec extends BasicValidation { 
    def validate(user: User): Validation[String, String] = { 
    for { 
     b <- checkAge(user) 
     c <- checkName(user) 
    } yield s"Congrats, ${c.name}" 
    } 
} 

trait BasicValidation { 
    def checkName(user: User): Validation[String, User] = { 
    if(user.name == "") "must have a name".fail else user.success 
    } 

    def checkAge(user: User): Validation[String, User] = { 
    if(user.age < 3) "must be a valid age".fail else user.success 
    } 
} 

的例外是

Error:(14, 25) Implicit not found: scalaz.Unapply[scalaz.Bind, 
scalaz.Validation[String,scalaz.validation.User]]. Unable to unapply type 
`scalaz.Validation[String,scalaz.validation.User]` into a type constructor of 
kind `M[_]` that is classified by the type class `scalaz.Bind`. Check that the 
type class is defined by compiling `implicitly[scalaz.Bind[type constructor]]` and 
review the implicits in object Unapply, which only cover common type 'shapes.' 
      b <- checkAge(user) 

Did i miss some implicit imports here ? 
         ^
+0

什麼版本的scalaz? – drstevens

+0

「org.scalaz」%「scalaz-core_2.10」%「7.1.0-M5」and scala core library is 2.10.2 –

+0

已更新我的回答7.1.0-M5/6 – drstevens

回答

6

驗證沒有綁定爲它定義。

在Scalaz 7.1.0-M5(M6太)Validation.flatMap已被棄用,在顛覆警告的嘗試,它看起來像的flatMap優先正在失去scalaz.syntax.bind._,這是Scalaz._進口的一部分。看到這個提交https://github.com/scalaz/scalaz/commit/2727b2451eba2aa159f3fbb62bf92790ac99dc7a。嘗試添加import scalaz.Validation.FlatMap._或只導入您需要的東西,例如

import scalaz.Validation 
import scalaz.syntax.validation._ 

我會建議使用的東西,除了Validation雖然,因爲這將可能唯一的原因,你在未來更多的問題。見下面的scalaz.\/

這確實與scalaz 7.0.5編譯。 Validation.flatMap在7.0.6中定義,所以它也應該與該版本一起編譯。儘管如此,我不會在新代碼中使用此功能(Validationfor解析中)。

scalaz的權力,有一段時間貶值Validation.flatMap gona來回現在。 flatMap是什麼讓它在for理解工作。 flatMapis deprecated in the working branch though。這方面有很長的背景。見https://groups.google.com/forum/#!topic/scalaz/Wnkdyhebo2w

TLDR - 驗證不是單子。 Validation.flatMap的任何可能的實現將不匹配爲Validation定義的Apply的行爲。

使用scalaz.\/(又名分離)如果你想使用for領悟。如果您需要累積錯誤,則使用Validation而不是\/的原因是,轉換爲Validation,然後返回\/

+0

@CareyGregory正在研究更多完整答案,但希望首先回復短版。我確實留下了他正在使用的特定版本的請求。它還回答了他的問題:「我錯過了一些隱含的進口嗎?」 – drstevens

+0

什麼是急於?這樣做讓你的答案被標記爲刪除,因爲它最初只是第一句話。 –

+0

@CareyGregory正如我所說的,它回答了這樣一個問題,即「我錯過了一些隱含的進口嗎?」你也可以提供更好的答案。 – drstevens