by runT1ME · 11y ago · 0 comments
You can write immutable java, but the language doesn't make it easy to at all. Look at the hilariously bad builder pattern (which is as good as it gets in Java) compared to the right way of doing things in Scala.
(for {
_ <- EventLenses.duid := UserDuid("12345")
_ <- EventLenses.contexts := Seq(EventContext.NilContext)
_ <- EventLenses.url := "http://news.ycombinator.com"
} yield ()).run(originalEvent)
This code will take an event, set it's duid, contexts and url. If you squint hard enough it almost looks like: originalEvent.duid = ...
originalEvent.contexts = ...
originalEvent.url = ...
The thing that's cool about lenses is that they compose nicely. E.g., the contexts lens is defined as: val contexts: Lens[Event, Seq[EventContext]] = query >=> getterMLens("cx") >=> Lens.lensu(...)
This means that first we take the query lens, compose it with a lens that gets the "cx" parameter, then do the actual work of decoding the "cx" param.