斯卡拉无形镜片不起作用

时间:2014-04-10 21:20:02

标签: scala shapeless lenses

在我的项目中,我遇到了一种情况,我需要对不可变对象执行嵌套更新,这是一个case类的实例。

首先,我只想使用案例类提供的copy函数,但后来我偶然发现了镜头。我查看ShapelessScalaz个实施,并决定尝试使用Shapeless中的镜头,因此我抓住了依赖项,将"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.full添加到build.sbt和根据{{​​1}}:https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#boilerplate-free-lenses-for-arbitrary-case-classes上的可用示例尝试编写简单的内容。

GitHub

但在编译过程中我遇到了错误:

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)
}

可能我错过了一些明显的东西,因为我从wiki复制粘贴了一个例子。

编辑:在Travis发表评论后,我使用https://github.com/jrudolph/sbt-dependency-graph为我的项目生成了依赖图,我发现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 ^ ^ 已经包含spray-routing库:

shapeless

所以我删除了我的依赖项并尝试了https://github.com/milessabin/shapeless/blob/scala-2.9.x/examples/src/main/scala/shapeless/examples/lenses.scala中的示例,现在它正常工作。

1 个答案:

答案 0 :(得分:1)

如果您将Lens[Person]替换为lens[Person](即小写l),则您的示例应该有效。为什么?你的无形依赖指向你刚刚发布的,但尚未公布或完全记录的无形2.0.0最终版本。嘘......不要告诉任何人; - )