Using monads

Scalaz defines quite a lot of different methods that can be applied directly to any monad we have. There are multiple examples that show lists and options. The library also has a Monad trait that can be extended. It is similar to the Monoid trait.

We don't want to dig into list examples that show how to use monads, though. To make things interesting, let's look at the IO monad in Scalaz that can be used to perform I/O in a monadic way. What this basically means is that we can describe and compose those actions without actually performing them. This will lead to better code reuse as well. Let's see an example:

import java.io.{PrintWriter, File}import scala.io.Sourcepackage object monads {  def readFile(path: String) = { System. ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.