Composing IO
Sequencing effects.
Sequencing with flatMap
Because IO is a monad, you compose effects with flatMap. Each step runs in order, and a later step can use the result of an earlier one.
import cats.effect.IO
val program: IO[Unit] =
IO("Alice").flatMap(name => IO.println(s"Hello, $name"))for-comprehension
A for-comprehension desugars to flatMap/map and reads like an imperative script while staying pure.
import cats.effect.IO
val prog: IO[Unit] = for {
_ <- IO.println("What is your name?")
name <- IO("Bob")
_ <- IO.println(s"Hi $name")
} yield ()