Skip to Content
Course content

101: Tagless Final Pattern Revisited In Depth

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

If you've been browsing Scala forums or reading functional libraries, you've probably seen the term "Tagless Final." It sounds like something out of a category theory textbook, and to be honest, the academic explanation usually makes it sound more complicated than it actually is. In practice, it's just a way to stop your business logic from caring about how your effects—like database calls, API requests, or logging—are actually executed.

The trap of hard-coding your effects

Most of us start by writing services that look something like this. Let's say we're building a simple system to handle user registrations. You'd probably write a repository that returns a Future because that's what your database driver provides.

case class User(id: UUID, email: String)

class UserRepository {
  def save(user: User): Future[Unit] = {
    // imagine some database logic here
    Future.successful(())
  }
}

class RegistrationService(repo: UserRepository) {
  def register(user: User): Future[Unit] = {
    println(s"Registering ${user.email}...")
    repo.save(user)
  }
}

At first glance, this is fine. It's readable and it works. But here is where I usually start seeing things break. Because Future is eager, the moment you call register, the side effect starts. If you want to write a unit test for RegistrationService, you're now forced to deal with asynchronous execution and potentially complex mocking of Future. More importantly, you've coupled your business logic to a specific concurrency primitive. If you later decide to move to ZIO or Cats Effect IO for better cancellation or resource management, you have to rewrite every single method signature in your entire application.

Abstracting the effect with F[_]

The "Tagless Final" way is to stop naming the effect. Instead of saying "this returns a Future," we say "this returns some F, and I don't care what F is, as long as it behaves like a Monad."

We do this by turning our service into a trait parameterized by a type constructor F[_]. I like to think of this as defining a "language" for our domain. We aren't running the program yet; we're just describing the steps.

import cats.Monad
import cats.implicits._

trait UserRepository[F[_]] {
  def save(user: User): F[Unit]
}

class RegistrationService[F[_]: Monad](repo: UserRepository[F]) {
  def register(user: User): F[Unit] = {
    for {
      _ <- Monad[F].pure(println(s"Registering...")) // Simplified logging
      _ <- repo.save(user)
    } yield ()
  }
}

Now, RegistrationService is completely agnostic. It doesn't know if it's running in a Future, an IO, or even a Id (the identity monad) for lightning-fast synchronous tests. We've shifted the responsibility of choosing the execution context from the service to the "edge" of the application—usually your main method or your dependency injection module.

The cost of flexibility

I'll be honest with you: this comes with a tax. You're now staring at F[_] and context bounds like [F[_]: Monad] everywhere. For a junior dev, this can look like alphabet soup. You also have to deal with implicit resolution, which can occasionally lead to some cryptic compiler errors if you forget to import cats.implicits._.

But the trade-off is worth it when you hit a certain scale. When I've had to migrate production systems from Future to ZIO, the projects using Tagless Final were a breeze—I just changed the interpreter at the top level. The projects that hard-coded Future required a week of surgical refactoring. You're essentially trading a bit of initial verbosity for total control over your runtime behavior.




📋 Practical Task

Implementing a Tagless Final Payment Processor

You are tasked with refactoring a legacy payment system. Currently, the PaymentService is hard-coded to use Future, making it impossible to test without a real network connection or complex mocks.

Your Goal: Convert the following "naive" implementation into a Tagless Final pattern using Cats.

// Naive implementation to refactor
class PaymentGateway {
  def charge(amount: Double): Future[Boolean] = Future.successful(true)
}

class PaymentService(gateway: PaymentGateway) {
  def processPayment(amount: Double): Future[String] = {
    gateway.charge(amount).map { success =>
      if (success) "Payment Successful" else "Payment Failed"
    }
  }
}

Requirements:

  1. Create a PaymentGateway[F[_]] trait.
  2. Rewrite PaymentService to be generic over F[_], requiring a Monad[F] context bound.
  3. Use a for-comprehension inside processPayment instead of .map to demonstrate the monadic flow.
  4. Implement a MockPaymentGateway that uses cats.Id (the identity monad) to prove the service can run synchronously for tests.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.