在我的项目中,我遇到了需要对作为案例类实例的不可变对象执行嵌套更新的情况。
首先,我只是想使用copy
案例类提供的功能,但后来我偶然发现了镜头。我查看了实现Shapeless
并Scalaz
决定我将尝试使用来自的镜头Shapeless
,所以我抓住了依赖项,添加"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.full
到我的build.sbt
并尝试根据以下可用示例编写一些简单的东西GitHub
:https ://github.com/milessabin/shapeless/wiki /功能概述:-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
^
^
可能我遗漏了一些明显的东西,因为我从 wiki 复制粘贴了一个示例。
编辑:在 Travis 发表评论后,我使用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中的示例,现在它可以正常工作了.