Created
July 11, 2023 21:29
-
-
Save majk-p/dfdcf08bdfc3986c3dcd94cc02fa4f52 to your computer and use it in GitHub Desktop.
Introduction to Optics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using scala "3.3.0" | |
//> using dep "dev.optics::monocle-core:3.2.0" | |
//> using dep "dev.optics::monocle-macro:3.2.0" | |
import monocle.syntax.all._ | |
case class Product(id: String, name: String, price: Double) | |
case class Shelf(id: String, product: Product) | |
case class Display(id: String, kind: "Ambient" | "Chilled", shelves: List[Shelf] ) | |
case class Alley(id: String, displays: List[Display]) | |
case class Shop(alleys: List[Alley]) | |
val water = Product("1", "Bottle of water", 6.99) | |
val milk = Product("2", "Milk 1l", 3.85) | |
val cheese = Product("3", "Cheese", 7.99) | |
val ham = Product("4", "Ham", 9.99) | |
val shop = Shop( | |
alleys = List( | |
Alley( | |
id = "1", | |
displays = List( | |
Display("1", "Ambient", List(Shelf("1", water), Shelf("2", milk))), | |
Display("2", "Chilled", List(Shelf("3", cheese), Shelf("4", ham))) | |
) | |
) | |
) | |
) | |
val discounted = | |
shop | |
.focus(_.alleys) | |
.each | |
.refocus(_.displays) | |
.each | |
.refocus(_.shelves) | |
.each | |
.refocus(_.product.price) | |
.modify(_ * 0.9) | |
println(discounted) |
fair nuff, although the example already uses union types 😅
That's also true! I planned to update the post with a clarification anyway 😁
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Me too! I only used the longer version because it also works for Scala 2 😉