Field Notes

Cats Core, Part 9: Ior, for Results That Arrive with Warnings

Cats Core, Part 9: Ior, for Results That Arrive with Warnings

Part 8 ended with Order. Before that, most of this series was about two outcomes: a value is valid, or it is not. Validated collects every reason it is not, and Either stops at the first one. Real imports have a third outcome that neither type can hold: I accepted this, but you should know something about it.

That third outcome is what cats.data.Ior is for. The Cats documentation calls it an inclusive-or: an Ior[A, B] holds an A, a B, or both. Either is the exclusive version. Like Either, it is right-biased: map and flatMap work on the right side.

Setup

Same versions as the rest of the series: Scala 2.13.18 and cats-core 2.12.0. My scratch sbt project already had the three constructors in Main.scala. For the longer experiments I used a single scala-cli file pinned to the same two versions. scala-cli printed a hint that cats-core 2.13.0 is out; I stayed on 2.12.0 so the outputs line up with the earlier parts.

val ior1: Ior[String, String] = Ior.both("bla", "bli")
val ior2: Ior[String, String] = Ior.left("bla")
val ior3: Ior[String, String] = Ior.right("bli")

List(ior1, ior2, ior3).foreach {
  case Ior.Left(a)    => println(s"$a only")
  case Ior.Right(b)   => println(s"$b only")
  case Ior.Both(a, b) => println(s"$a and $b")
}

Three shapes, and the pattern match has to handle all three. With Either there are two cases; here you have to decide what Both means in your domain.

A contract import with warnings

I reused the Contract from Part 8 and split the checks into two severities. A negative premium is an error: the contract is rejected. A zero premium or a start year before 2020 is suspicious, but the contract still goes in, with a note.

import cats.data.{Ior, IorNec}
import cats.implicits._

final case class Contract(id: String, premium: BigDecimal, startYear: Int)

val MinYear = 2020

def checkPremium(c: Contract): IorNec[String, Contract] =
  if (c.premium < 0) Ior.leftNec(s"${c.id}: negative premium ${c.premium}")
  else if (c.premium == 0) Ior.bothNec(s"${c.id}: zero premium, check pricing", c)
  else Ior.right(c)

def checkYear(c: Contract): IorNec[String, Contract] =
  if (c.startYear < MinYear) Ior.bothNec(s"${c.id}: start year ${c.startYear} before $MinYear", c)
  else Ior.right(c)

def importContract(c: Contract): IorNec[String, Contract] =
  for {
    a <- checkPremium(c)
    b <- checkYear(a)
  } yield b

Ior.leftNec and Ior.bothNec wrap the message in a NonEmptyChain, so each check returns an IorNec[String, Contract], the same shape as ValidatedNec from Part 6. Four contracts through importContract printed:

ctr-001 -> Right(Contract(ctr-001,25,2022))
ctr-002 -> Both(Chain(ctr-002: start year 1991 before 2020),Contract(ctr-002,25,1991))
ctr-003 -> Both(Chain(ctr-003: zero premium, check pricing, ctr-003: start year 1991 before 2020),Contract(ctr-003,0,1991))
ctr-004 -> Left(Chain(ctr-004: negative premium -5))

ctr-003 is the interesting one. Both checks fired, both were warnings, and both messages arrived in order with the contract still attached. That accumulation needs a Semigroup on the left side, which is why Cats requires one for Ior's Monad and Applicative instances. NonEmptyChain has one.

Three cards showing flatMap on Ior: Right runs the next step, Both runs the next step and combines its warnings with the next result's left side, Left stops.
flatMap on Both keeps going and appends; on Left it stops, exactly like Either.

Reporting the three outcomes

At the edge of the program the three shapes turn into three messages. This is what I like about Ior compared with logging warnings as a side effect: the warnings travel with the value, and the caller decides what to do with them.

contracts.map(importContract).foreach {
  case Ior.Right(c)   => println(s"${c.id} imported")
  case Ior.Both(w, c) => println(s"${c.id} imported with warnings: ${w.mkString_("; ")}")
  case Ior.Left(e)    => println(s"rejected: ${e.mkString_("; ")}")
}
ctr-001 imported
ctr-002 imported with warnings: ctr-002: start year 1991 before 2020
ctr-003 imported with warnings: ctr-003: zero premium, check pricing; ctr-003: start year 1991 before 2020
rejected: ctr-004: negative premium -5

Where Ior is not Validated

My first assumption was that Ior is "Validated with a bonus". It is not, and mapN shows why:

val w:  IorNec[String, Int] = Ior.bothNec("w1", 1)
val e1: IorNec[String, Int] = Ior.leftNec("e1")
val e2: IorNec[String, Int] = Ior.leftNec("e2")

(w, e1).mapN(_ + _)   // Left(Chain(w1, e1))
(e1, e2).mapN(_ + _)  // Left(Chain(e1))
(w, w).mapN(_ + _)    // Both(Chain(w1, w1),2)

(e1.toValidated, e2.toValidated).mapN(_ + _)  // Invalid(Chain(e1, e2))

Two independent errors give you only the first one. Ior's Applicative is consistent with its Monad, so mapN behaves like a chain of flatMaps: a Left stops everything after it. What it does keep is any warning that came before the error, hence Left(Chain(w1, e1)). It is the Applicative-versus-Monad trade-off from the ValidatedNec post, seen from the other side.

Table comparing mapN results for IorNec, ValidatedNec and Either on three input pairs: warning then warning, warning then error, and error then error.
Ior keeps warnings; Validated keeps every independent error. Neither does both.

So the choice is about what you need to collect. Independent field checks where the user wants every problem at once: Validated. A pipeline where later steps depend on earlier ones and warnings must survive: Ior.

Gotcha 1: traverse rejects the whole batch

Once each contract returns an IorNec, traverse looks like the natural way to import a list. It works while there are only warnings, and fails in a way I did not expect once there is an error:

List(clean, oldOne, zeroOld).traverse(importContract)
// Both(Chain(ctr-002: start year 1991 before 2020,
//            ctr-003: zero premium, check pricing,
//            ctr-003: start year 1991 before 2020),
//      List(Contract(ctr-001,25,2022), Contract(ctr-002,25,1991), Contract(ctr-003,0,1991)))

List(clean, oldOne, broken, zeroOld).traverse(importContract)
// Left(Chain(ctr-002: start year 1991 before 2020, ctr-004: negative premium -5))

One bad contract turns the whole result into a Left. ctr-001 and ctr-002 are lost even though they were fine, and ctr-003, which comes after the broken one, is never checked: its warnings are not in the output. If each contract stands on its own, map to a List[IorNec[String, Contract]] and report per item, as in the reporting example. Use traverse only when the batch really is all-or-nothing.

Gotcha 2: conversions drop the warnings

w.toEither   // Right(1)
w.toOption   // Some(1)
w.left       // Some(Chain(w1))
w.pad        // (Some(Chain(w1)),Some(1))

The docs say it directly: converting to Either, Validated or Option discards the left value when both sides are present. If an API boundary forces you into Either, read the warnings out first with .left or .pad. Otherwise they disappear without any error.

Remember it as

Ior is an Either that can also say "yes, but". It carries warnings forward and stops at the first error; it does not collect independent errors the way Validated does.

Recall check

  1. What is Ior.bothNec("w1", 1).flatMap(_ => Ior.leftNec[String, Int]("e1"))?
  2. From Part 8: with implicit val byPremium: Order[Contract] = Order.by(_.premium), why can two contracts with different ids be ===?

Takeaways

  • Ior has three cases: Left (errors only), Right (value only) and Both (warnings plus a value).
  • flatMap and for-comprehensions carry Both forward and combine the left sides with a Semigroup; IorNec gives you one.
  • mapN short-circuits on the first Left. For every independent error, use Validated.
  • traverse over a batch lets one error reject everything; map when items are independent.
  • toEither, toValidated and toOption silently drop warnings.

Answers: (1) Left(Chain(w1, e1)): the warning is kept and the error is appended. (2) Order extends Eq and derives equality from compare, which only looks at the premium.

Keep reading