Monocle is a Scala library which offers a simple yet powerful API to access and transform immutable data.
import monocle.syntax.all._
val user = User("Anna", Address(12, "high street"))
user.focus(_.name).replace("Bob")
// res: User = User("Bob", Address(12, "high street"))
user.focus(_.address.streetName).modify(_.toUpperCase)
// res: User = User("Anna", Address(12, "HIGH STREET"))
user.focus(_.address.streetNumber).get
// res: Int = 12
Installation
Monocle is published for Scala 2.13.x and 3.x. You can add it to your sbt build with:
libraryDependencies ++= Seq(
"dev.optics" %% "monocle-core" % "3.1.0",
"dev.optics" %% "monocle-macro" % "3.1.0",
)
You also need this compiler option if you want to use macro annotations - only available for Scala *2.13:
Global / scalacOptions += "-Ymacro-annotations"
Copyright and license
All code is available to you under the MIT license, available here. The design is informed by many other projects, in particular Haskell Lens.
Copyright the maintainers, 2016 - 2021.