Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Last active December 12, 2017 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvolpe/240607df25e26118b347927b3af09ac8 to your computer and use it in GitHub Desktop.
Save gvolpe/240607df25e26118b347927b3af09ac8 to your computer and use it in GitHub Desktop.
Function to PartialFunction
private def liftToPF[X <: Y, W, Y](f: Function[X, W])(implicit ct: ClassTag[X]): PartialFunction[Y, W] =
new PartialFunction[Y, W] {
override def isDefinedAt(x: Y): Boolean = ct.runtimeClass.isInstance(x)
override def apply(v1: Y): W = f(v1.asInstanceOf[X])
}
sealed trait MyError
case class ErrorOne(msg: String) extends MyError
case class ErrorTwo(msg: String) extends MyError
case class ErrorThree(msg: String) extends MyError
val errorHandler: MyError => F[Response[F]] = {
case ErrorOne(msg) => BadRequest(msg)
case ErrorTwo(msg) => NotFound(msg)
}
// When using recoverWith from ApplicativeError you can get matching exhaustiveness. Eg with Http4s:
users.flatMap(x => Ok(x.asJson)).recoverWith(liftToPF(errorHandler))
// match may not be exhaustive.
// [warn] It would fail on the following input: ErrorThree(_)
// [warn] val errorHandler: MyError => F[Response[F]] = {
// [warn] ^
// [warn] one warning found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment