Cats Documentation
repository·main·Indexed 26 days ago
https://github.com/typelevel/catsA fundamental library for functional programming in Scala providing essential abstractions like type classes and functional patterns. It includes core modules such as cats-core, cats-kernel, and cats-laws, as well as specialized tools like IorT for error accumulation, Eval for controlled laziness, and the algebra package for representing mathematical structures. Compatible with JVM, Scala.js, and Scala Native.
What's inside Cats
- Cats is a library providing core functional programming abstractions for the Scala programming language. It is designed to be binary compatible, modular, approachable, and efficient, serving as a foundation for a broader ecosystem of pure, typeful functional programming libraries in Scala.
Understand Type Classes and Ad-hoc Polymorphism
mainType classes enable ad-hoc polymorphism (overloading) in functional programming. Unlike object-oriented subtyping, type classes allow you to define behavior for a type without modifying the type itself. This is achieved by separating the data (the type) from the behavior (the type class instance).Use the Reducible type class
mainThe
Reducibletype class extendsFoldableto provide reduction methods that do not require an initial value (unlikefold). This makes it ideal for abstracting over non-empty collections likeNonEmptyListorNonEmptyVector.Key characteristics:
- Unlike
Foldablewhich requires aMonoid(forfold),Reducibleonly requires aSemigroup(forreduce). - It provides guarantees that operations won't throw exceptions on empty collections when used with non-empty types.
- It includes eager reduction (
reduceLeft) and lazy reduction (reduceRight) usingEval.
import cats._ import cats.data._ import cats.syntax.all._ // Example usage with NonEmptyList Reducible[NonEmptyList].reduce(NonEmptyList.of("a", "b", "c"))- Unlike
Understand the Validated data type
mainThe
Validated[+E, +A]data type is used for error accumulation. It is similar toEither, but unlikeEither(which is a Monad and follows a fail-fast approach),Validatedis an Applicative Functor. This allows it to collect multiple errors instead of stopping at the first one encountered.It has two projections:
Valid[+A](a: A): Represents a successful computation.Invalid[+E](e: E): Represents a failed computation containing error(s).
Note: Because it is not a Monad, you cannot use for-comprehensions (which rely on
flatMap) to composeValidatedinstances. Instead, you must use Applicative syntax like.mapN.sealed abstract class Validated[+E, +A] extends Product with Serializable final case class Valid[+A](a: A) extends Validated[Nothing, A] final case class Invalid[+E](e: E) extends Validated[E, Nothing]Understand the Foldable type class
mainThe
Foldable[F]type class is implemented for data structures that can be folded into a summary value. It is primarily built upon two core methods:foldLeft(fa, b)(f): Performs an eager, left-associative fold overfa.foldRight(fa, b)(f): Performs a lazy, right-associative fold overfa.
For a collection like
List(1, 2, 3)with a starting value0and addition+:foldLeftexecutes as((0 + 1) + 2) + 3.foldRightexecutes as0 + (1 + (2 + 3)).
If you are defining a new data structure, providing implementations for
foldLeftandfoldRightallows you to automatically gain access to a wide range of otherFoldableoperations.Understand NonEmptyList
mainA
NonEmptyList[A]is a specialized data type that guarantees at least one element exists by construction. This makes it a safer alternative toList[A]for operations that are undefined for empty collections (likehead).Key benefits:
- Totality: Operations like
headandtailare always well-defined because an emptyNonEmptyListcannot be created. - Error Reporting: It is ideal for use with
ValidatedorIorto ensure that anInvalidstate always contains at least one error. - Domain Logic: It allows you to move validation to the boundaries of your program, enabling functions to accept
NonEmptyListinstead ofListandOption, thus avoiding unnecessary null/empty checks in your core logic.
- Totality: Operations like
Understand and use the Ior data type
mainThe
Ior[A, B]data type represents an inclusive-or relationship. UnlikeEither, which is exclusive (eitherAorB), anIorcan contain anA, aB, or both anAand aB.Ioris right-biased, meaningmapandflatMapoperate on the right side (B). When usingMonadorApplicativeinstances,Ioraccumulates values on the left side (requiring aSemigroupforA), similar to howValidatedworks. This allows you to accumulate non-fatal warnings on the left while continuing with the computation on the right.import cats.data._ val right = Ior.right[String, Int](3) val left = Ior.left[String, Int]("Error") val both = Ior.both("Warning", 3)Understand Kleisli as a Monad Transformer
mainIn Cats,Kleisli[F, A, B]can be viewed as a monad transformer for functions. It represents a function of typeA => F[B]. This allows you to compose the monadic properties ofF[_]with the function's input/output, enabling you to work with nested contexts or effects (likeOption,Either, orList) within a function's execution flow.Explore the Typelevel Ecosystem libraries
mainThe Typelevel ecosystem includes a variety of specialized Scala libraries for functional programming. Key libraries include:
- sttp: A Scala HTTP client.
- sup: Composable, purely functional healthchecks.
- tsec: Typesafe, functional, general purpose cryptography and security.
- vault: Type-safe, persistent storage for values of arbitrary types.
- upperbound: A purely functional, interval-based rate limiter with backpressure support.
- streamz: Conversion between Akka Streams and Fs2 Streams/Pipes/Sinks, and support for Apache Camel endpoints.
- synchronized: Synchronous resource access.
- system-effect: Console and Environment Simple Tools.
- testcontainers-specs2: Test Containers support for Specs2.
- unique: Unique functional values for Scala.
- vinyldns: DNS governance system using Fs2 for throttling updates.
- whale-tail: Docker Daemon Integration.
Use the Writer datatype for logging computations
mainThe
Writer[L, A]datatype represents a computation that produces a tuple containing a value of typeA(the output) and a value of typeL(the logging side). When composing operations likeflatMap, the logs are automatically combined using an implicitSemigroup[L].To access the contents of a
Writer, use the.runmethod.import cats.data.Writer import cats.instances._ val mapExample = Writer("map Example", 1).map(_ + 1) mapExample.runUnderstand the `Const` data type
mainThe
Const[A, B]data type is a container that stores a value of typeAbut carries a phantom type parameterB. The type parameterBis not used in the data structure itself, but it allows you to carry type information through functional transformations. It behaves similarly to theconstfunction, which returns the first argument and ignores the second.case class Const[A, B](getConst: A)Explore the Typelevel Ecosystem libraries
mainThe Typelevel ecosystem consists of various purely functional libraries designed to work together. This segment of the ecosystem includes tools for parsing, concurrency, JSON manipulation, and more:
- Mules: In-memory caching.
- agitation: Cooperative Cancelation for Cats Effect.
- ancient-concurrent: Cats Effect concurrency for cats-effect 0.10.
- atto: Friendly text parsers.
- bank: Concurrent Vault Management.
- canoe: Purely functional library for building Telegram chatbots.
- Cats Effect: High-performance, asynchronous, composable framework for building real-world applications in a purely functional style.
- cats-effect-testing: Experimental integration between Cats Effect and testing frameworks.
- cats-effect-time: Java Time for Cats Effect.
- cats-parse: A parsing library for the Cats ecosystem.
- cats-retry: Composable retry logic for Cats and Cats Effect.
- cats-scalacheck: Cats typeclass instances for ScalaCheck.
- cats-stm: Software Transactional Memory for Cats Effect.
- cats-time: Cats typeclass instances for
java.time. - chromaprint: Scala implementation of Chromaprint/AcoustID audio fingerprinting, built with Fs2 streams and Cats Effect.
- circe-fs2: Streaming JSON manipulation with Circe.
- Circe: Pure functional JSON library.
- circuit: Functional Circuit Breaker implementation.