CA

Cats

Cats typeclass library patterns for functional abstractions and effect composition in Scala

Details

Language / Topic
scalaScala
Category
Libraries

Rules

balanced
- Import `cats.implicits._` or targeted imports like `import cats.syntax.either._` — prefer targeted imports in production to reduce compile times.
- Use `Validated[E, A]` over `Either[E, A]` when accumulating errors: `(nameV, ageV).mapN(User.apply)` collects all failures.
- Use `IO` from `cats-effect` for side-effecting code — wrap impure calls with `IO(sideEffect())` and compose with `flatMap` or `*>`.
- Prefer `Traverse[F].traverse` over `map + sequence`: `list.traverse(fetchUser)` is cleaner than `list.map(fetchUser).sequence`.
- Use `Monoid[A].combine` and `Foldable.fold` for aggregations — lets you switch collection type without changing aggregation logic.
- Use `EitherT[F, E, A]` to combine `F[Either[E, A]]` into a monad transformer — call `.value` to extract the wrapped `F`.
- Use `NonEmptyList[A]` (NEL) when the list is guaranteed non-empty — avoids defensive `headOption.getOrElse` calls at call sites.
- Derive typeclass instances with `cats.derived` for `Eq`, `Show`, `Order`, and `Monoid` on case classes without boilerplate.