Skip to Content
Course content

72: Cats Type Classes: Functor, Applicative, Monad

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

I once worked with a developer who spent three days writing a complex data ingestion pipeline. He had these deep, nesting blocks of flatMap and map that looked like a staircase moving off the right side of the screen. When I asked him to add a new validation step, he sighed and told me he was terrified of touching it because he couldn't keep track of which "layer" of the Either or Option he was currently in. He was treating the wrappers as annoying obstacles rather than tools. That's the moment I realized he didn't need more syntax—he needed to understand the patterns that Cats formalizes as Functors, Applicatives, and Monads.

The Power of Abstract Mapping with Functors

You've used .map a thousand times on List or Option, but in Cats, a Functor is the formalization of that ability. A Functor is essentially any type F[A] that allows you to transform the value inside it without changing the structure of the wrapper.

Now, you might ask, "Why do I need a type class for this when I can just call .map?" The magic happens when you write generic code. Imagine you're writing a utility to "clean" a string, but you don't know if that string is wrapped in an Option, a List, or a Future. By requiring a Functor[F], you can write a function that works for all of them:

import cats.Functor

def cleanData[F[_]: Functor](input: F[String]): F[String] = {
  Functor[F].map(input)(_.trim.toLowerCase)
}

// This now works for any Functor!
val opt = cleanData(Option("  Hello  ")) // Some("hello")
val list = cleanData(List("  A  ", "  B  ")) // List("a", "b")

I like to think of Functors as the "shallowest" level of interaction. You're just reaching inside the box, changing the item, and putting it back. You aren't changing the box itself, and you certainly aren't creating new boxes.

Combining Independent Effects with Applicatives

This is where things get interesting. A Monad (which we'll hit in a second) is great for sequential steps, but what happens when you have three independent API calls and you want to combine their results? If you use flatMap, you end up with that "staircase of doom" I mentioned earlier.

An Applicative allows you to treat these effects as independent. If you have three Either[Error, A] values, an Applicative can combine them into a single Either[Error, (A, B, C)]. If any of them fail, the whole thing fails, but the logic remains flat. In Cats, we often use mapN for this. It's a lifesaver for form validation or gathering configuration settings.

import cats.Applicative
import cats.implicits._

case class UserProfile(name: String, age: Int, email: String)

def validateName(n: String): Either[String, String] = if (n.nonEmpty) Right(n) else Left("Empty name")
def validateAge(a: Int): Either[String, Int] = if (a > 0) Right(a) else Left("Invalid age")
def validateEmail(e: String): Either[String, String] = if (e.contains("@")) Right(e) else Left("Invalid email")

// Using Applicative mapN to combine results independently
val result = (validateName("Alice"), validateAge(30), validateEmail("a@b.com")).mapN(UserProfile.apply)
// Right(UserProfile("Alice", 30, "a@b.com"))

Notice how we didn't have to nest three flatMaps. We just said: "Here are three things that might fail; if they all succeed, put them in this case class."

Sequential Dependency and the Monad

Finally, we have the Monad. While Applicatives are for independent actions, Monads are for dependent actions. If the result of the first call determines what the second call should be, you need a Monad. This is what flatMap (or bind in Cats terminology) provides.

In the real world, this is your classic "Fetch user from DB, then use that user's ID to fetch their orders" flow. You can't fetch the orders until you have the user. The Monad allows you to chain these dependencies while keeping the error handling (the Either or Option) consistent across the whole chain.

The trick to remembering the difference is this: Functor transforms a value; Applicative combines independent values; Monad chains dependent values. If you find yourself nesting flatMaps for things that don't actually depend on each other, stop and ask yourself if you should be using an Applicative instead. Your future self (and your teammates) will thank you for the flatter code.




📋 Practical Task

Implementing a Multi-Step Order Validation Pipeline

You are building a checkout system for an e-commerce site. You need to implement a validation process that uses both Applicative and Monadic patterns.

Requirements:

  • Create three validation functions that return Either[String, A]:
    • checkInventory(itemId: String): Either[String, Int] (Returns quantity available or "Out of Stock").
    • checkCoupon(code: String): Either[String, Double] (Returns discount percentage or "Invalid Coupon").
    • checkShippingAddress(addr: String): Either[String, String] (Returns the address if valid, or "Invalid Address").
  • First, use mapN (Applicative) to combine the checkCoupon and checkShippingAddress results into a ShippingDetails case class. These two checks are independent.
  • Second, use flatMap (Monad) to ensure that checkInventory is called only if the shipping details were validated successfully.
  • The final result should be an Either[String, OrderSummary] where OrderSummary contains the final quantity and the shipping details.

Constraint: Do not use nested if/else blocks or manual pattern matching to combine the Either values; use the Cats type class operators.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.