Map a Future for both Success and Failure

后端 未结 4 2044
闹比i
闹比i 2021-01-30 22:38

I have a Future[T] and I want to map the result, on both success and failure.

Eg, something like

val future = ... // Future[T]
val mapped = future.mapAll         


        
4条回答
  •  野的像风
    2021-01-30 22:50

    In a first step, you could do something like:

    import scala.util.{Try,Success,Failure}
    
    val g = future.map( Success(_):Try[T] ).recover{
      case t => Failure(t)
    }.map {
      case Success(s) => ...
      case Failure(t) => ...
    }
    

    where T is the type of the future result. Then you can use an implicit conversion to add this structure the Future trait as a new method:

    implicit class MyRichFuture[T]( fut: Future[T] ) {
      def mapAll[U]( f: PartialFunction[Try[T],U] )( implicit ec: ExecutionContext ): Future[U] = 
        fut.map( Success(_):Try[T] ).recover{
          case t => Failure(t)
        }.map( f )
     }
    

    which implements the syntax your are looking for:

    val future = Future{ 2 / 0 }
    future.mapAll {
      case Success(i) => i + 0.5
      case Failure(_) => 0.0
    }
    

提交回复
热议问题