在我的項目中,我遇到了一個情況,我需要對不可變對象(它是case類的一個實例)執行嵌套更新。scala無形鏡頭不工作
首先,我只是想使用案例類提供的copy
功能,但後來我偶然發現了鏡頭。我擡頭Shapeless
和Scalaz
實現和決定,我會嘗試用鏡頭從Shapeless
,所以我抓住的依賴,增加"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.full
我build.sbt
並試着寫一些簡單的基礎上,提供例如在GitHub
:https://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現在的例子它工作正常。
錯誤中的'Iso'表明你實際上使用1.2.4。 –
有趣的是,當我使用'IDEA'進入'Lens'類時,我處於'shapeless_2.10-1.2.4'神器。 – Andna