0

在我的项目中,我遇到了需要对作为案例类实例的不可变对象执行嵌套更新的情况。

首先,我只是想使用copy案例类提供的功能,但后来我偶然发现了镜头。我查看了实现ShapelessScalaz决定我将尝试使用来自的镜头Shapeless,所以我抓住了依赖项,添加"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.full到我的build.sbt并尝试根据以下可用示例编写一些简单的东西GitHubhttps ://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中的示例,现在它可以正常工作了.

4

1 回答 1

1

如果您在整个过程中都替换Lens[Person]lens[Person](即小写),那么您的示例应该可以工作。l为什么?您的 shapeless 依赖项将您指向刚刚发布但尚未宣布或完整记录的 shapeless-2.0.0 最终版本。嘘......不要告诉任何人;-)

于 2014-04-10T21:38:42.450 回答