Does Shapeless 2.0.0 lens work with lists / collections?

If I have this:

case class Foo( age: Int, name: String, bar: List[Bar], alive: Boolean ) case class Bar( hey: String, you: String ) 

Is it possible to create a lens that can get / set foo.bar(1).you ?

+5
source share
1 answer

Not out of the box, and you really need a partial lens to look at things in a list by index responsibly. Scalaz provides what you need, and shapeless-contrib simplifies the interaction:

 import scalaz.PLens._ import shapeless.lens import shapeless.contrib.scalaz._ val secondBar = (lens[Foo] >> 'bar).asScalaz.partial.andThen(listNthPLens(1)) 

And then:

 scala> secondBar.get(fooB) res0: Option[Bar] = None scala> secondBar.get(fooA) res1: Option[Bar] = Some(Bar(foo,bar)) scala> secondBar.set(fooA, Bar("bar", "foo")) res2: Option[Foo] = Some(Foo(1,,List(Bar(,), Bar(bar,foo)),false)) scala> secondBar.set(fooB, Bar("bar", "foo")) res3: Option[Foo] = None 

If you do not mind living dangerously, you can also write your own Shapeless lens to search for locations in a list (with a type like Lens[List[A], A] ), but this will give great value for both Barren and lenses.

+7
source

Source: https://habr.com/ru/post/1205405/


All Articles