Search code examples
scalapartialfunction

How to use PartialFunction.applyOrElse


I have a PartialFuncton[Throwable,Future[Result]] called errorMap to transform an throwable to a result or failed future. I can do it via lift and getOrElse like this:

val x: Future[Result] = errorMap.lift(e).getOrElse(Future.failed(e))

I figure the same should be achievable with applyOrElse, but I can't seem to figure out how to call it to achieve this end. Am I misunderstanding what applyOrElse is for?


Solution

  • The second argument to applyOrElse takes a function-- in your case a (Throwable) => Future[Result]

    Pass it a function like this:

    errorMap.applyOrElse(e, _ => Future.failed(e))

    or simply

    errorMap.applyOrElse(e, Future.failed)