Type Classes

What Does It Mean to Be an Effect?

The type class hierarchy in Cats Effect defines formal rules that describe what it means to be a functional effect. This is analogous to how mathematics has axioms for numbers (e.g., commutativity of addition).

When you work with IO, Resource, Kleisli, or any other effectful structure, you can rely on it satisfying certain laws. This enables:

Categories of Effect Capabilities

Cats Effect organizes effect capabilities into six main categories, ordered by increasing power (each subsequent category assumes the previous ones):

1. Resource Safety & Cancellation

Foundational level for all other capabilities. Enables:

Key type classes: MonadCancel, Spawn

2. Parallel Computation

Enables running multiple effects concurrently and coordinating their execution:

Key type classes: Spawn, Concurrent

3. Shared State

Synchronization primitives for safe data exchange between concurrent processes:

Key type classes: Concurrent

4. Time

Working with temporal dimensions:

Key type classes: Clock, Temporal

5. Safe Interfacing with Synchronous Side Effects — Sync Effects

Transforming ordinary synchronous code with side effects into a pure functional description:

Key type classes: Sync, Defer

6. Safe Interfacing with Asynchronous Side Effects — Async Effects

Integration with callback-based async APIs:

Key type classes: Async

Why This Order?

The hierarchy is built so that it is impossible to express a more powerful concept through a less powerful one without "cheating":

Key insight: The higher the level, the more guarantees you get, but fewer effect types can support it. For example, StateT can be a Monad, but it cannot be Async, because it cannot work with real time and side effects.

Capabilities from Cats Core

Before discussing effects, Cats Effect relies on basic abstractions from the Cats library:

Type class What it provides Usage example
Functor map — value transformation fa.map(_ + 1)
Apply ap — function application in context, product — combining effects (fa, fb).mapN(_ + _)
Applicative pure — lifting a value into a context Applicative[IO].pure(42)
Monad flatMap — sequential composition with dependencies fa.flatMap(a => fb.map(b => a + b))
MonadError raiseError / handleError — error handling fa.handleErrorWith(e => IO.pure(0))

These capabilities form the foundation upon which the entire ecosystem is built. Without them, effects would just be "sealed computations" without combinability.

Functional Effect Hierarchy

graph TB
    subgraph cats-core
        A[Functor] --> B[Apply] --> C[Applicative] --> D[Monad] --> E[MonadError]
    end
    
    subgraph cats-effect
        E --> J[MonadCancel]
        J ----> F[Sync]

        F --> H[Async]
        
        J --> K[Spawn]
        K --> L[Concurrent]
        L --> G[Temporal]
        G --> H[Async]

        I[Clock] --> F
        I --> G
        
        M[Unique] --> K
        M --> F
        
        N[Defer] --> F
    end

Key capabilities added at each level:

Type class Key operation What it provides
Clock realTime, monotonic Working with time (wall-clock and monotonic time)
Sync delay, blocking, suspend Lazy synchronous evaluation, isolating side effects, blocking code
Unique unique Generating unique tokens (e.g., for identification)
Defer defer Lazy effect creation, deferring computation until execution
MonadCancel cancelable, uncancelable, onCancel Effect cancellation, protecting critical sections, registering finalizers
Spawn start, racePair, never, cede Spawning fibers, races, cooperative multitasking
Concurrent ref, deferred, semaphore, cancelable Synchronization primitives (Ref, Deferred, Semaphore) and cancellable async calls
Temporal sleep, timeout, timeoutTo Delays, timeouts, working with time
Async async, evalOn, executionContext Async FFI (callback → F[A]), thread pool switching, Future integration

Practical Significance of the Hierarchy

For Effect Users

You can precisely express requirements for code:

// Require cancellation — cannot pass a plain monad
def withTimeout[F[_]: Temporal](fa: F[String]): F[String] =
  fa.timeout(1.second)

// Require everything — only IO or similar
def runServer[F[_]: Async](port: Int): F[Unit] = ...

For Library Authors

You can write maximally generic code:

For Understanding Code

Looking at a method signature, you immediately understand what it can do:

Summary: Laws as the Foundation of Reliability

When you write (1 + 2) + 3, you don't think about whether it will use an Intel or ARM processor. The laws of arithmetic guarantee the same result.

Similarly, when you use MonadCancel, you know, for example, that:

This enables:

Cats Effect is not just an IO library. It is a language for describing effects with formal semantics.


Links: