Last active
December 12, 2017 19:22
-
-
Save gvolpe/240607df25e26118b347927b3af09ac8 to your computer and use it in GitHub Desktop.
Function to PartialFunction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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