私のプロジェクトでは、ケース クラスのインスタンスである不変オブジェクトに対してネストされた更新を実行する必要がある状況に遭遇しました。
最初は、ケース クラスによって提供される関数を使用したかったcopy
のですが、レンズに出くわしました。実装を調べてShapeless
、のScalaz
レンズを使用しようと決めたShapeless
ので、依存関係を取得"com.chuusai" % "shapeless" % "2.0.0" cross CrossVersion.full
して自分に追加し、次build.sbt
の入手可能な例に基づいて簡単なものを書き込もうとしましたGitHub
: https://github.com/milesabin/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
^
^
wiki から例をコピーして貼り付けたので、おそらく明らかな何かが欠けています。
編集: Travis からのコメントの後、https://github.com/jrudolph/sbt-dependency-graphspray-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の例を試してみましたが、正しく動作するようになりました.