Monads for Java developers: Part 2 — Two monads more

Summary of Part 1

  • Monads refer to types that wrap values such as Optional and Stream in Java.
  • The monad provides a context to the value: Optional<String> provides an Optional context to the String it wraps.
  • A monad has to implement bind (flatMap) and unit. Also it has to comply with three laws: Left identity, Right identity and associativity.
  • Monads benefits are clearer when composing them because they help us forget about the context. Composition in this case refers to function composition[1] and not to OOP composition.

The Result class

See the full implementation with all the methods here: https://gist.github.com/afcastano/59ea31314f583a40a3a929eb25147417
See the Result full implementation including flatMap here: https://gist.github.com/afcastano/604ac9cb72a0aae9fbeb0e2d78ccb9d9
See the full implementation with all methods here: https://gist.github.com/afcastano/1b3ee98f7bae8b1547f9d149d5508d5b

The Log class

Value: 3.5
Trace: [initial value: 5, run operation by adding 2: 7,
divided by 4: 1.75, Multiplied by two: 3.5]
Value: 6.0
Trace: [initial value: 5, 2a -> add 2: 7, 2b -> add 5: 12,
divided by 4: 3.0, Multiplied by two: 6.0]
See the full implementation here: https://gist.github.com/afcastano/9dd29d2e4eabe95459909bf6534f9955

To finalise

Notes:

Recommended reads:

--

--

--

Software developer at Square. https://andrescastano.dev

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Castaño

Castaño

Software developer at Square. https://andrescastano.dev

More from Medium

Who Shot Rest? Let’s Discover gRPC

InjectIntoKeyValue in Eclipse Collections

Matrix URIs, their semantics and usage in Java RESTful Services

Logging in Camel on Spring-Boot using the Fuse Logger