2014-04-10 15 views
0

在我的項目中,我遇到了一個情況,我需要對不可變對象(它是case類的一個實例)執行嵌套更新。scala無形鏡頭不工作

首先,我只是想使用案例類提供的copy功能,但後來我偶然發現了鏡頭。我擡頭ShapelessScalaz實現和決定,我會嘗試用鏡頭從Shapeless,所以我抓住的依賴,增加"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.fullbuild.sbt並試着寫一些簡單的基礎上,提供例如在GitHubhttps://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#boilerplate-free-lenses-for-arbitrary-case-classes

object LenseExamples extends App { 
    import shapeless._ 

    // A pair of ordinary case classes ... 
    case class Address(street : String, city : String, postcode : String) 
    case class Person(name : String, age : Int, address : Address) 

    // Some lenses over Person/Address ... 
    val nameLens  = Lens[Person] >> 0 
    val ageLens  = Lens[Person] >> 1 
    val addressLens = Lens[Person] >> 2 
    val streetLens = Lens[Person] >> 2 >> 0 
    val cityLens  = Lens[Person] >> 2 >> 1 
    val postcodeLens = Lens[Person] >> 2 >> 2 

    val person = Person("Joe Grey", 37, Address("Southover Street", "Brighton", "BN2 9UA")) 

    val age1 = ageLens.get(person) 
} 

但在編譯過程中我得到這樣的錯誤:

inferred type arguments [Nothing,Int] do not conform to method >>'s type parameter bounds [L <: shapeless.HList,N <: shapeless.Nat] 
    val nameLens  = Lens[Person] >> 0 
           ^
type mismatch; 
found : Int(0) 
required: N 
    val nameLens  = Lens[Person] >> 0 
            ^
could not find implicit value for parameter iso: shapeless.Iso[api.LenseExamples.Person,L] 
    val nameLens  = Lens[Person] >> 0 
           ^         
           ^

也許我缺少明顯的東西,因爲我是從維基複製粘貼的例子。

編輯:特拉維斯評論後,我產生依賴圖使用https://github.com/jrudolph/sbt-dependency-graph我的項目,我觀察到spray-routing已經包括shapeless庫:

[info] +-io.spray:spray-routing:1.3.0 [S] 
[info] | +-com.chuusai:shapeless_2.10:1.2.4 [S] 
[info] | | +-org.scala-lang:scala-library:2.10.0 (evicted by: 2.10.4) 
[info] | | +-org.scala-lang:scala-library:2.10.3 (evicted by: 2.10.4) 

於是我打消了我的依賴,並試圖從https://github.com/milessabin/shapeless/blob/scala-2.9.x/examples/src/main/scala/shapeless/examples/lenses.scala現在的例子它工作正常。

+1

錯誤中的'Iso'表明你實際上使用1.2.4。 –

+0

有趣的是,當我使用'IDEA'進入'Lens'類時,我處於'shapeless_2.10-1.2.4'神器。 – Andna

回答

1

如果您在整個過程中將Lens[Person]替換爲lens[Person](即小寫字母l),您的示例應該可以正常工作。爲什麼?你的無形依賴性指向你剛剛發佈的,但尚未公佈或完全記錄的無形-2.0.0最終版本。噓......別告訴任何人;-)

+0

嘿,謝謝你的回答。事實證明,我的問題是'spray-routing'已經把'shapeless'庫拉到了我的項目中,但是在不同的版本中:'1.2.4'。我看了這個版本的例子,現在鏡頭工作正常。 – Andna