Blog

Type-safe error handling with Shapeless coproducts in Scala

Introduction

Error handling is often not given the attention that it deserves. Coming from imperative languages, it’s super easy to throw exceptions all over the place. Still, because it’s easy, it doesn’t mean it’s a good practice. It breaks referential transparency, making it difficult to reason about code. Java has checked exceptions, but that is not making the problem disappear, as it still breaks referential transparency. There are many more reasons why “just throwing exceptions” is not a good practice, but I’ll not go into that today. My concern with using exceptions is that, in many cases, we are not talking about the “exceptional” part embedded in the word “exception”.

Let’s have a look at the Cambridge definition of the word “exception”. If we look at technical exceptions, I can fully agree with the last part of the definition:

Exception: “Someone or something that is not included in a rule, group, or list or that does not behave in the expected way.” — Cambridge Dictionary

Hereby are a few examples of unexpected behaviours due to technical issues:

  • While saving data to a database, the connection goes down, failing to persist the data.
  • While uploading images to a server, the connection gets interrupted, failing to send the image entirely.
  • While processing a Kafka message, the client gets killed, failing to process the message.

These are all examples of processes that somehow did not behave expectedly. The exception here is due to a technical issue. Looking at a pure domain, however, many exceptions are not exceptions.

Below you can find a few examples of everyday situations that did not behave expectedly:

  • Before registering a new user, we validate the data and realize that a field is missing, sending back a 400 bad request to the client.
  • While processing a financial transaction, the system suspects something is off, informs the users that something went wrong and automatically notifies the fraud team to investigate the transaction.
  • When trying to pay with a gift card, the system notices that there’s not enough balance on the gift card to complete the order, and the user is informed accordingly.

The above examples are part of domains where we anticipate that these situations can happen and are therefore expected. Even though the chance of them happening might be small, these are still situations we expect to happen. Instead of misusing exceptions, we can make errors part of our domain and introduce the concept of a domain error. The advantage of using a different type (i.e. anything that is not inheriting from Throwable) is that we need to handle them explicitly. There’s no way we can throw them; therefore, we cannot use any try/catch construction. There’s, however, a downside when using sealed traits.

In this article, we’ll be creating a straightforward command-line app to divide numbers. We’ll go through a few iterations of code, and I’ll show you the problems we will run into and how Shapeless coproducts can help us out.

Domain errors are everywhere

Why would we want to use domain errors again? Let’s have a look at the method below:

def divide(x: Int, y: Int) = x / y

The above code is concise and readable, but we do not inform the consumer of our method that it can produce errors. Dividing by zero should not be possible. An ArithmeticException will be thrown if the consumer dares to try. However, that doesn’t make much sense. We already know that we can’t divide by zero, so that’s not an exception. It’s part of our domain, and we should inform our fellow programmers that we do not allow divisions by zero. Making it explicit will help our colleagues understand that the method requires error handling. We should always strive to create error handlers that are total functions. This way, the compiler can help us if we accidentally do not handle all errors. Otherwise, you’ll lose any benefit, and you can just as well use exceptions.

Why sealed traits are not the best option

A common way to deal with errors is using a sealed trait. Looking at our little “number dividing” command-line app, we know that we can run into at least two issues:

  • Converting input from the command line into a number can go wrong
  • Dividing by zero is not possible

By introducing a sealed trait, we could document these errors in our codebase as follows:

sealed trait DomainError
<code><span>case object DivideByZeroError extends DomainError
</span><span>case class ParseNumberError(value: String) extends DomainError</span>

By using traits, we need to start thinking about structuring the error hierarchy.

  • Do all domain errors inherit from a root? (e.g. DomainError in the above example)
  • Do we introduce subdomains of errors that might or might not have a common ancestor? (e.g. per endpoint, per functionality, or maybe something else?)

In either case, we will not be delighted.

In the first scenario, we will not be able to accurately describe which errors we might get back the moment we start composing methods. As all errors inherit from DomainError, we will be unable to understand which errors can actually occur. See the example below for further details.

<span>sealed trait DomainError
case class ErrorA() extends DomainError
</span><span>case class ErrorB() extends DomainError
</span><span>case class ErrorC() extends DomainError
</span><span>
</span><span>object SomeClass {
</span><span>  def methodA(s: String): Either[ErrorA, String] = if (s.isEmpty) Left(ErrorA()) else Right(s)
</span><span>  def methodB(s: String): Either[ErrorB, Int] = s.toIntOption.fold[Either[ErrorB, Int]](Left(ErrorB()))(Right.apply)
</span><span>
</span><span>  // This method has to return DomainError and is no longer accurate, as it can only ever return ErrorA or ErrorB.
</span><span>  def methodAB(s: String): Either[DomainError, Int] = methodA(s).flatMap(methodB)
</span><span>}</span>

In the second scenario, we will have difficulties composing methods. The moment subdomains start interacting, we will need to cast them to a new error that is known by the other subdomain. Meaning we will start introducing duplication per interaction, as a DivideByZeroError in domain A, which will also need to exist in domain B once they start interacting. We could “solve” the problem by introducing a common ancestor, but that would lead us to the problem of the previous scenario.

The lack of visibility on which errors are returning is not something to overlook. A method returning DomainError in a codebase where we could have hundreds of domain errors defined provides no help whatsoever. The consumer of our approach would have to inspect our code to understand which domain errors can actually occur. At the same time, our compiler can no longer help us out if we accidentally forget about an error case. Total functions become useless if we start including cases that can never appear. In large codebases, it’s also impossible to go through numerous layers of code to figure out what will be returned. This slows you down as a programmer and, at the same time, gives you nothing but a gut feeling. Did you check everything thoroughly? Would it be possible that you have overlooked an error case? Just think about automatically updating dependencies, and you’ll quickly realize that you would need to continuously go through 3rd party code to figure out what you can expect from an error perspective.

Let errors become first-class citizens! If we can make everything explicit, we don’t run into any of the above problems. If dependencies get updated, and new error cases were introduced, then you’ll automatically run into compile errors, as our full function handling the errors is no longer covering all cases. No time wasted. And you know exactly where to fix what. Unfortunately, in Scala 2.x, there is no class or type class that we could use:

  • The Option type class deals with the optionality of a single type. We, however, already know that a method could likely produce more than a single error. When composing methods, the likeliness will increase even more.
  • The Either type class has a left and right projection, where the left can be used for error cases. Its left projection has only space for a single type, while we need more.
  • The List type class can store multiple values, but only for a single type.

We need some kind of structure EitherN that allows us to return numerous error types instead that can be unrelated and do not need a common ancestor. This is exactly what we are going to achieve with Shapeless coproducts.

What is an HList?

To handle different errors, we would need a List structure that can store different types and not lose any type-safety. Let’s have a look at the HList type class. It provides a way to create a list of more than a single type. Remember that the List type class in Scala always provides a list of a specific type (e.g. List[Int]). With HList, we can create lists of more than a single type.

See the example below for a list that contains multiple values (1, "world", 1.5) of different types (String, Int, Double):

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">shapeless.HNil</span><span>import shapeless.::
</span><span>val hlist: String :: Int :: String :: Double :: HNil = "hello" :: 1 :: "world" :: 1.5 :: HNil</span>

What is a coproduct?

Coproduct is a special kind of HList. You can think of it as an Either in Scala, with an arbitrary number of choices.

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">shapeless.</span><span style="color: inherit;font-family: inherit;background-color: inherit">{</span><span style="color: inherit;font-family: inherit;background-color: inherit">:</span><span style="color: inherit;font-family: inherit;background-color: inherit">+:</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">CNil</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">Coproduct</span><span style="color: inherit;font-family: inherit;background-color: inherit">}</span><span>
</span><span>type MyType = String :+: Int :+: Double :+: CNil
</span><span>val coproduct: MyType = Coproduct[MyType](1.5)</span>

In the code above, the coproduct will either contain a String, Int or a Double value.

<span></span>

Iterations

Let’s play with code, go through 7 iterations, and try to improve the code each time as much as possible.

Iteration 1: No error handling

Let’s go back to our divide app and start without thinking about any error handling at all:

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">scala.io.StdIn.readLine</span><span>
</span><span>object DivideAppIteration1 extends App {
</span><span>  // Can throw an ArithmeticException when dividing by zero.
</span><span>  def divide(x: Double, y: Double): Double = x / y
</span><span>
</span><span>  // Potential IOException when using readLine.
</span><span>  val x0 = readLine
</span><span>  val y0 = readLine
</span><span>
</span><span>  // Potential parse errors when converting String to Double.
</span><span>  val x = x0.toInt
</span><span>  val y = y0.toInt
</span><span>
</span><span>  println(divide(x, y))
</span><span>}</span>

We already know that this code is not resilient:

  • We are not preventing division by zero.
  • We are not catching parse errors.
  • We are not catching the potential IOException that can occur.

Did you know that readLine can throw an IOException? It’s not obvious at all from the actual method signature:

<span>def</span><span> readLine</span><span>()</span><span>:</span><span> </span><span>String</span><span> </span><span>=</span><span> in</span><span>.</span><span>readLine</span><span>()</span>

By diving one level deeper, we’ll see the following Java code:

<span>public String readLine() throws IOException {
</span><span>  return readLine(false, null);
</span><span>}</span>

This perfectly demonstrates the need to make errors first-class citizens of a program. By not knowing explicitly which error cases can occur, you will run into runtime errors or have to scan each line of code yourself. Not only in your code but also in all the libraries you might use. Not really an option if you like to get things done…

Iteration 2: Using Either

Let’s have another go at our application and make it a bit more robust by using the Either type class:

<span>import scala.io.StdIn.readLine
</span><span>import scala.util.Try
</span><span>
</span><span>object DivideAppIteration2 extends App {
</span><span>  // Using sealed traits to distinguish the type of errors
</span><span>  sealed trait DomainError
</span><span>
</span><span>  case object DivideByZeroError extends DomainError
</span><span>
</span><span>  case class ParseNumberError(value: String) extends DomainError
</span><span>
</span><span>  // Dividing an error now explicitly shows what kind of error it could produce.
</span><span>  def divide(x: Double, y: Double): Either[DomainError, Double] =
</span><span>    if (y == 0) Left(DivideByZeroError)
</span><span>    else Right(x / y)
</span><span>
</span><span>  // This now, unfortunately became an Object due to the mixing of DomainError and IOException
</span><span>  def runDivide: Either[Object, Double] = for {
</span><span>    x0 <- Try(readLine).fold(Left.apply, Right.apply)
</span><span>    y0 <- Try(readLine).fold(Left.apply, Right.apply)
</span><span>    x <- x0.toDoubleOption
</span><span>           .fold[Either[ParseNumberError, Double]](Left(ParseNumberError(x0)))(Right.apply)
</span><span>    y <- y0.toDoubleOption
</span><span>           .fold[Either[ParseNumberError, Double]](Left(ParseNumberError(y0)))(Right.apply)
</span><span>    r <- divide(x, y)
</span><span>  } yield r
</span><span>
</span><span>  runDivide.fold(
</span><span>    // As err is of type Object, we cannot create any sensible error handler based on the type
</span><span>    err => println(s"An error occurred: $err"),
</span><span>    result => println(s"Result: $result")
</span><span>  )
</span><span>}</span>

Even though the above code runs fine, the runDivide method has turned into an untyped mess. Object does not accurately describe what kind of errors we can expect. This is because DomainError and IOException have only Object in common from an inheritance point of view.

Iteration 3: Creating type-safety with coproducts

Let’s have a look at how we can improve type-safety with Shapeless coproducts:

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">shapeless.</span><span style="color: inherit;font-family: inherit;background-color: inherit">{</span><span style="color: inherit;font-family: inherit;background-color: inherit">:</span><span style="color: inherit;font-family: inherit;background-color: inherit">+:</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">CNil</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">Coproduct</span><span style="color: inherit;font-family: inherit;background-color: inherit">}</span><span>
</span><span>import java.io.IOException
</span><span>import scala.io.StdIn.readLine
</span><span>import scala.util.Try
</span><span>
</span><span>object DivideAppIteration3 extends App {
</span><span>  // Notice that creating a sealed trait error hierarchy is no longer necessary.
</span><span>  case object DivideByZeroError
</span><span>
</span><span>  case class ParseNumberError(input: String)
</span><span>
</span><span>  // Definition of the errors that can occur
</span><span>  type TryDivideError = DivideByZeroError.type :+: CNil
</span><span>  type TryReadLineError = IOException :+: CNil
</span><span>  type TryParseNumberError = ParseNumberError :+: CNil
</span><span>
</span><span>  def tryDivide(x: Double, y: Double): Either[TryDivideError, Double] =
</span><span>    if (y == 0) Left(Coproduct(DivideByZeroError))
</span><span>    else Right(x / y)
</span><span>
</span><span>  def tryReadLine = Try(readLine).fold[Either[TryReadLineError, String]](
</span><span>    ex => Left(Coproduct(new IOException(ex))),
</span><span>    Right.apply
</span><span>  )
</span><span>
</span><span>  def tryParseDouble(s: String) =
</span><span>    s.toDoubleOption.fold[Either[TryParseNumberError, Double]](
</span><span>      Left(Coproduct(ParseNumberError(s)))
</span><span>    )(Right.apply)
</span><span>
</span><span>  type RunDivideError = TryReadLineError :+: TryParseNumberError :+: TryDivideError :+: CNil
</span><span>
</span><span>  // Yes! We now have an actual error type that accurately describes the error cases.
</span><span>  def runDivide: Either[RunDivideError, Double] = for {
</span><span>    x0 <- tryReadLine.left.map(Coproduct[RunDivideError](_))
</span><span>    y0 <- tryReadLine.left.map(Coproduct[RunDivideError](_))
</span><span>     x <- tryParseDouble(x0).left.map(Coproduct[RunDivideError](_))
</span><span>     y <- tryParseDouble(y0).left.map(Coproduct[RunDivideError](_))
</span><span>     r <- tryDivide(x, y).left.map(Coproduct[RunDivideError](_))
</span><span>  } yield r
</span><span>
</span><span>  runDivide.fold(println, println)
</span><span>}</span>

Each method still explicitly describes what its error signature is. The big difference is that we have now introduced a new coproduct RunDivideError that is either one of the coproducts that each particular method produces (either a TryReadLineError, TryParseNumberError or TryDivideError or):

<span style="color: inherit;font-family: inherit;background-color: inherit">// Each individual error defined.</span><span>type TryDivideError = DivideByZeroError.type :+: CNil
</span><span>type TryParseNumberError = ParseNumberError :+: CNil
</span><span>type TryReadLineError = IOException :+: CNil
</span><span>
</span><span>// A composition of errors we expect for the divide 'flow'.
</span><span>type RunDivideError = TryDivideError :+: TryReadLineError :+: TryParseNumberError :+: CNil</span>

To return a RunDivideError, we must ensure that every method’s result is widened. We can do that by wrapping the result in a new coproduct like:

<span>Coproduct</span><span>[</span><span>RunDivideError</span><span>](</span><span>resultOfTheMethod</span><span>)</span><span> </span><span>//</span><span> </span><span>Widens</span><span> the </span><span>type</span><span> </span><span>returned</span><span> </span><span>from</span><span> </span><span>the</span><span> </span><span>method.</span>

There’s a slight “gotcha” here. As coproducts are nothing more than a special kind of HList, defining RunDivideErrors below means we could have duplicate types in our error channel. This isn’t necessarily a problem, but it would be at least good to mention it.

<span>TryDivideError</span><span> </span><span>:</span><span>+:</span><span> </span><span>TryReadLineError</span><span> </span><span>:+:</span><span> </span><span>TryParseNumberError</span><span> </span><span>:+:</span><span> </span><span>CNil</span>

Let’s create a simple example that quickly illustrates the potential issue of type duplication and how we can solve it:

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">shapeless.</span><span style="color: inherit;font-family: inherit;background-color: inherit">{</span><span style="color: inherit;font-family: inherit;background-color: inherit">:</span><span style="color: inherit;font-family: inherit;background-color: inherit">+:</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">CNil</span><span style="color: inherit;font-family: inherit;background-color: inherit">,</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">Coproduct</span><span style="color: inherit;font-family: inherit;background-color: inherit">}</span><span>
</span><span>// Error definitions, there's a bit of overlap on the types.
</span><span>type Method1Error = String :+: Int :+: CNil
</span><span>type Method2Error = String :+: Double :+: CNil
</span><span>type Method3Error = String :+: Int :+: Double :+: CNil
</span><span>
</span><span>def method1 = Coproduct[Method1Error]("error 1")
</span><span>def method2 = Coproduct[Method2Error]("error 2")
</span><span>def method3 = Coproduct[Method3Error]("error 3")
</span><span>
</span><span>// Wrapping in a new coproduct.
</span><span>type StringErrors = Method1Error :+: Method2Error :+: Method3Error :+: CNil
</span><span>val result1: String :+: Int :+: String :+: Double :+: String :+: Int :+: Double :+: CNil = Coproduct[StringErrors](method1).adjoined
</span><span>val result2: String :+: Int :+: String :+: Double :+: String :+: Int :+: Double :+: CNil = Coproduct[StringErrors](method2).adjoined
</span><span>val result3: String :+: Int :+: String :+: Double :+: String :+: Int :+: Double :+: CNil = Coproduct[StringErrors](method3).adjoined
</span><span>
</span><span>// Embedding in an existing coproduct.
</span><span>type StringError = String :+: Int :+: Double :+: CNil
</span><span>val result4: String :+: Int :+: Double :+: CNil = method1.embed[StringError]
</span><span>val result5: String :+: Int :+: Double :+: CNil = method2.embed[StringError]
</span><span>val result6: String :+: Int :+: Double :+: CNil = method3.embed[StringError]</span>

In the example above, you can see that there’s quite a difference between the two approaches.

Wrapping the result in a new coproduct creates a bigger coproduct:

<span>String</span><span> </span><span>:</span><span>+:</span><span> </span><span>Int</span><span> </span><span>:+:</span><span> </span><span>String</span><span> </span><span>:+:</span><span> </span><span>Double</span><span> </span><span>:+:</span><span> </span><span>String</span><span> </span><span>:+:</span><span> </span><span>Int</span><span> </span><span>:+:</span><span> </span><span>Double</span><span> </span><span>:+:</span><span> </span><span>CNil</span>

Embedding flattens the coproduct and only returns the unique types:

<span>String</span><span> </span><span>:</span><span>+:</span><span> </span><span>Int</span><span> </span><span>:+:</span><span> </span><span>Double</span><span> </span><span>:+:</span><span> </span><span>CNil</span>

Notice that the adjoined method is used to turn the type StringErrors into a flattened coproduct to demonstrate that there’s type duplication.

Iteration 4: Embedding coproducts

We’re only interested in a flattened representation of our domain errors for our app, so instead of wrapping coproducts, we’ll use the embed function.

<span style="color: inherit;font-family: inherit;background-color: inherit">import</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">shapeless.ops.adjoin.Adjoin</span><span>import shapeless.{:+:, CNil, Coproduct, Poly1}
</span><span>
</span><span>import java.io.IOException
</span><span>import scala.io.StdIn.readLine
</span><span>import scala.util.Try
</span><span>
</span><span>object DivideAppIteration4 extends App {
</span><span>  case object DivideByZeroError
</span><span>
</span><span>  case class ParseNumberError(input: String)
</span><span>
</span><span>  type TryDivideError = DivideByZeroError.type :+: CNil
</span><span>
</span><span>  def tryDivide(x: Double, y: Double): Either[TryDivideError, Double] =
</span><span>    if (y == 0) Left(Coproduct(DivideByZeroError))
</span><span>    else Right(x / y)
</span><span>
</span><span>  type TryReadLineError = IOException :+: CNil
</span><span>
</span><span>  // Fold on Try will always give us a Throwable and is no longer an IOException.
</span><span>  // For educational purposes I'm not going to bother doing anything about this and
</span><span>  // I'll just wrap the exception into an IOException again.
</span><span>  def tryReadLine = Try(readLine).fold[Either[TryReadLineError, String]](
</span><span>    ex => Left(Coproduct(new IOException(ex))),
</span><span>    Right.apply
</span><span>  )
</span><span>
</span><span>  type TryParseNumberError = ParseNumberError :+: CNil
</span><span>
</span><span>  def tryParseDouble(s: String) =
</span><span>    s.toDoubleOption.fold[Either[TryParseNumberError, Double]](
</span><span>      Left(Coproduct(ParseNumberError(s)))
</span><span>    )(Right.apply)
</span><span>
</span><span>  // Flattens the types.
</span><span>  val runDivideError = Adjoin[TryReadLineError :+: TryParseNumberError :+: TryDivideError]
</span><span>  // Uses the resulting Out as our type signature.
</span><span>  type RunDivideError = runDivideError.Out
</span><span>
</span><span>  // We're now using the embed method instead.
</span><span>  def runDivide: Either[RunDivideError, Double] = for {
</span><span>    x0 <- tryReadLine.left.map(_.embed[RunDivideError])
</span><span>    y0 <- tryReadLine.left.map(_.embed[RunDivideError])
</span><span>    x <- tryParseDouble(x0).left.map(_.embed[RunDivideError])
</span><span>    y <- tryParseDouble(y0).left.map(_.embed[RunDivideError])
</span><span>    r <- tryDivide(x, y).left.map(_.embed[RunDivideError])
</span><span>  } yield r
</span><span>
</span><span>  // An error handler to demonstrate how we could deal with errors.
</span><span>  object errorHandler extends Poly1 {
</span><span>    implicit def ioException = at[IOException] { e =>
</span><span>      println(s"An IOException occurred: ${e.getMessage}")
</span><span>    }
</span><span>
</span><span>    implicit def parseDoubleError = at[ParseNumberError] { e =>
</span><span>      println(s"Cannot parse '${e.input}' as an integer")
</span><span>    }
</span><span>
</span><span>    implicit def divideByZeroError = at[DivideByZeroError.type] { _ =>
</span><span>      println("Cannot divide by zero")
</span><span>    }
</span><span>  }
</span><span>
</span><span>  runDivide.fold(_.fold(errorHandler), println)
</span><span>}</span>

There’s still a bit of noise in the code above. For a start, we have to widen the type for every method invocation. This doesn’t compose too well. Let’s see what happens when we try to read the line and parse the input as a new composition:

<span style="color: inherit;font-family: inherit;background-color: inherit">def</span><span style="color: inherit;font-family: inherit;background-color: inherit"> runDivide</span><span style="color: inherit;font-family: inherit;background-color: inherit">:</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">Either</span><span style="color: inherit;font-family: inherit;background-color: inherit">[</span><span style="color: inherit;font-family: inherit;background-color: inherit">RunDivideError</span><span style="color: inherit;font-family: inherit;background-color: inherit">, </span><span style="color: inherit;font-family: inherit;background-color: inherit">Int</span><span style="color: inherit;font-family: inherit;background-color: inherit">]</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">=</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">for</span><span style="color: inherit;font-family: inherit;background-color: inherit"> </span><span style="color: inherit;font-family: inherit;background-color: inherit">{</span><span>  x <- tryReadLine
</span><span>         .leftMap(_.embed[RunDivideError])
</span><span>         .flatMap(tryParseInt(_).leftMap(_.embed[RunDivideError]))
</span><span>  y <- tryReadLine
</span><span>         .leftMap(_.embed[RunDivideError])
</span><span>         .flatMap(tryParseInt(_).leftMap(_.embed[RunDivideError]))
</span><span>  r <- tryDivide(x, y).leftMap(_.embed[RunDivideError])
</span><span>} yield r</span>

That doesn’t look too nice, to be honest. It’s not only cumbersome to widen our types by hand all the time, but it also introduces noise that makes it challenging to reason over our program.

Iteration 5: Reducing noise by introducing a syntax helper

How can we reduce the noise in the previous example? One way of solving this would be to let the methods already do the embedding themselves:

Even though this looks much better than previous versions, it would be great if we could eliminate the redundant RunDivideError that we have to pass to every single method when composing the methods.

Iteration 6: Reducing noise by moving the implicits

Can we reduce the noise even more? Yes, we can if we start moving the implicits around. We can do this rather simple by adding the implicits in the runDivide signature:

Unfortunately, we have to write tryParseNumber(_) for the type inference to work, and we cannot simply pass tryParseNumber as a function.

Iteration 7: Turning it into a REST API

The beauty of a functional program is that we can describe what our program should do, independent of our technology stack. In this last iteration, you’ll see how quickly we can turn our command-line app into a simple REST API, without much effort. We’ll use the Akka HTTP hello-world example as our base, but you can use any framework.

Conclusion

We have looked at Shapeless coproducts and saw that it is a union type (e.g. it can return more than a single type). This can be handy when a method can return more than a single error. In this article, we’ve created a simple command-line application and went through quite a few iterations of improvements. With little to no change, we saw how easy it is to move the code from our command-line application to a REST API due to functional composition.

The great question remains: Should I use Shapeless coproducts in my codebase?

The answer to that is: It depends

  • Suppose I was still on Scala 2.x. In that case, I’d try to get the codebase to Scala 3.0. This migration should be quite straightforward if you are on 2.13.8 (keep in mind that the most effortless migration is to 3.0 instead of a later 3.x release). Using native union types in Scala 3.x is a better solution as it doesn’t pollute the code in such an unfortunate way. I’ll do a follow-up soon with the same code in Scala 3.x, and you’ll see what a breeze it is to use.
  • If you’re still bound to Scala 2, using Shapeless could be a great way to create a type-safe error channel.

Whether having a type-safe error channel (i.e. “effects tracking”) is good or bad is heavily debated:

I’m still not entirely sure where I stand here. I think that making errors explicit just to make them explicit is not a good practice. However, I see value in making explicit errors that need to be accounted for upstream (i.e. by the callee or even higher up in the chain). As in many cases, whether it makes sense depends on what you try to do.

guest
0 Comments
Inline Feedbacks
View all comments

Explore related posts