0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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 ()

All lessons in this course

  1. Cats Type Classes
  2. The IO Monad
  3. Composing IO
  4. Error Handling in IO
← Back to Scala for Backend Engineering & Functional Programming