Skip to Content
Course content

73: Cats Effect IO Monad

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this exact pattern dozens of times with engineers transitioning to Cats Effect. You've got the types right, the logic looks sound, but when you hit 'Run', the console is stubbornly empty. Let's look at a piece of code that attempts to fetch a user from a database and log the result.

import cats.effect._

case class User(name: String)

object UserSystem extends IOApp.Simple {
  def fetchUser(id: Int): IO[User] = 
    IO.pure(User("Alice"))

  def run: IO[Unit] = {
    val userIO = fetchUser(1)
    
    // I want to print the user's name here
    userIO.map(user => println(s"Fetched user: ${user.name}"))
    
    IO.unit
  }
}

The Invisible Side Effect

If you run this, nothing happens. You'll see the program start and immediately exit with no output. Why? Because you've fallen into the "Blueprint Trap."

In Scala, a standard function executes its body immediately. But an IO is not a value; it's a description of a computation. When you call fetchUser(1), you aren't actually fetching a user; you're creating a recipe that says "If someone ever runs me, I will fetch a user."

The real bug is here: userIO.map(user => println(...)). The .map method creates a new IO that describes the act of printing. But you never told the IOApp runtime to actually execute that new IO. You just created a blueprint for a print statement and then immediately threw that blueprint away by returning IO.unit.

Turning the Blueprint into Action

To fix this, we need to do two things. First, we need to stop using println (a side-effecting function) inside a .map. In the world of Cats Effect, we use IO.println, which returns an IO[Unit]. Since we are now returning an IO inside another IO, we switch from .map to .flatMap.

Second, we must ensure the final resulting IO is the one returned by the run method, so the runtime knows to execute it.

import cats.effect._

case class User(name: String)

object UserSystem extends IOApp.Simple {
  def fetchUser(id: Int): IO[User] = 
    IO.pure(User("Alice"))

  def run: IO[Unit] = {
    val userIO = fetchUser(1)
    
    // We flatMap because IO.println returns another IO
    userIO.flatMap(user => IO.println(s"Fetched user: ${user.name}"))
  }
}

Chaining Sequential Effects

Now that it works, you might be wondering why we bother with this overhead. The power of the IO monad is that it allows us to compose complex, asynchronous programs while keeping them pure. Because IO is a monad, we can chain a series of dependent steps together without worrying about the underlying execution thread.

Think of flatMap as a "then" operator. "Fetch the user, then use that user to fetch their settings, then log the result." If any step in that chain fails, the entire sequence fails gracefully, and you can handle that error in one place using .handleErrorWith, rather than wrapping every single line in a try-catch block.

I usually tell my mentees: if you find yourself using .map to call a function that returns Unit or performs a side effect, you're almost certainly doing it wrong. If it does something in the real world, it belongs in a flatMap as an IO.




📋 Practical Task

Build a Sequential User Profile Aggregator

Your task is to simulate a profile aggregation service. You need to create three functions that return IO types and chain them together sequentially.

  • fetchUser(id: Int): IO[User] - Returns a user object.
  • fetchUserPosts(user: User): IO[List[String]] - Takes a user and returns a list of their post titles.
  • logSummary(user: User, posts: List[String]): IO[Unit] - Prints a summary like "User Alice has 3 posts."

Implement an IOApp.Simple where the run method chains these three calls together. The posts must be fetched using the result of the user fetch, and the summary must be logged using the results of both previous calls. Ensure no side effects occur outside of the IO monad (use IO.println, not println).

Rating
0 0

There are no comments for now.

to be the first to leave a comment.