0
votes

I have a case class like:

case class Person(name, birthDate, many other fields) { def something = //compute it from the fields }

What i would really like in the end is to have lenses for name, birthDate, and a readonly lens for something, and if possible compose them together to have a single lens for setting name/birthDate and reading name/birthDate/something

From my limited knowledge it does not seem possible (in shapeless i get an error when creating lens for the something function)

Maybe it's possible in other lens libraries or maybe there's a refactor i need to do

1

1 Answers

0
votes

Considering that optics in general solve the issue of two-way access (getting/settings something if possible), there is no such thing as read only lenses.

So, whether you use shapeless or Monocle or something else you cannot do it this way.

However, nothing stops you from doing:

// updates person
(lens1 composeLens lens2 composeLens personLens).modify(...)
// gets Person and reads "read only" property
(lens1 composeLens lens2 composeLens personLens).get(object).something 

About optics in general there is a nice article about them and how you can use them with Monocles.

EDIT. Well, perhaps you could design something to have "read only" optics - that is Prism which always fails to update, but that would be a terrible abomination of the idea I believe. Then you would not work on Person but on some coproduct of Person, but that would be awkwardly counter intuitive, so I do not even start to think how could it be implemented.