Optics for nested optional fields

1,100 views
Skip to first unread message

Valentin Kasas

unread,
Jan 16, 2015, 8:24:48 AM1/16/15
to scala-...@googlegroups.com
Hello,

I'm new to Monocle (and optics in general) and I experience some difficulties/frustration with nested optional fields.

Imagine I have the following : 


case class Bar(maybeStr: Option[String])
case class Foo(maybeBar: Option[Bar])

val barLenser = Lenser[Bar]
val fooLenser = Lenser[Foo]

val _maybeStr = barLenser(_.maybeStr)
val _maybeBar = fooLenser(_.maybeBar)


And I want to focus on the String that is (possibly) in the Bar that is (possibly) inside a Foo.

The less unsatisfying solution I came up with is the following

_maybeBar.modify(_.map(_maybeStr.set(Some("Modified String"))))(myFooInstance)

I'm confident there is a better solution to that quite simple problem, but I'd greatly appreciate if someone here could help me to find it.

Cheers.


Valentin

Julien Truffaut

unread,
Jan 16, 2015, 4:07:57 PM1/16/15
to Valentin Kasas, scala-...@googlegroups.com
Hi Valentin,

Yes there is a simpler solution. As you noticed, you cannot use lenses to zoom into an option because the option might be empty. However, you can compose your lenses with some from monocle.std.option. Some is a Prism and when you compose a Prism with a Lens (or the other way around) you get an Optional.

In your case you can do:

import monocle.std.option.some

(_maybeBar composePrism some composeLens _maybeStr composePrism some).set("Modified String")(myFooInstance)

Cheers


--
You received this message because you are subscribed to the Google Groups "Scala-Monocle" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-monocl...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Julien Truffaut
Tel : +44 7715 54 88 58 (UK)

Valentin Kasas

unread,
Jan 17, 2015, 6:52:32 AM1/17/15
to Julien Truffaut, scala-...@googlegroups.com
Hi Julien,

Thanks a lot for that swift answer, this make much more sense now.
Besides the https://hackage.haskell.org/package/lens documentation, where can I find more information about optics, their implementation in monocle and common use cases for each kind of optic ?

Cheers

Reply all
Reply to author
Forward
0 new messages