title: Failing a Future based on a successful result
body: <p>I have a scenario in my code where I need to make a <code>Future</code> fail based on a successful result that contains a certain value.  I can make this work just fine via <code>flatMap</code>, but I want to know if there is a cleaner way to make this work.  First, a very simplified example:</p>
  
  <pre><code>import concurrent._
  
  case class Result(successful:Boolean)
  object FutureTest {
    def main(args: Array[String]) {
      import ExecutionContext.Implicits._
  
      val f = Future{Result(false)}.flatMap{ result =&gt;
        result match{
          case Result(false) =&gt; Promise.failed(new Exception("The call failed!!")).future
          case _ =&gt; Promise.successful(result).future
        }
      }
  
      f onFailure{
        case x =&gt; println(x.getMessage())
      }
    }
  }
  </code></pre>
  
  <p>So in my example here, I want the <code>Future</code> to be failed if the <code>Result</code> returned has a value of <code>false</code> for its success indicator.  As I mentioned, I can make this work okay with <code>flatMap</code>, but the line of code I would like to eliminate is:</p>
  
  <pre><code>case _ =&gt; Promise.successful(result).future
  </code></pre>
  
  <p>This statement seems unnecessary.  The behavior that I would like is to be able to define the condition and if it evaluates to true, allow me to return a different <code>Future</code> as I am doing, but if it's not true, just leave things as they are (sort of like <code>PartialFunction</code> semantics.  Is there a way to do this that I'm just not seeing?  I've looked at <code>collect</code> and <code>transform</code> and those don't seem to be the right fit either.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>After getting the <code>map</code> suggestion from @Rex Kerr and @senia, I created a <code>PimpedFuture</code> and an implicit conversion to pretty up the code a bit like so:</p>
  
  <pre><code>class PimpedFuture[T](f:Future[T])(implicit ex:ExecutionContext){
    def failWhen(pf:PartialFunction[T,Throwable]):Future[T] = {
      f map{
        case x if (pf.isDefinedAt(x)) =&gt; throw pf(x)
        case x =&gt; x
      }
    }
  }
  </code></pre>
  
  <p>The implicit</p>
  
  <pre><code>  implicit def futToPimpedFut[T](fut:Future[T])(implicit ec:ExecutionContext):PimpedFuture[T] = new PimpedFuture(fut)
  </code></pre>
  
  <p>And the new handling code:</p>
  
  <pre><code>val f = Future{ Result(false) } failWhen {
    case Result(false) =&gt; new Exception("The call failed!!")
  }
  </code></pre>
  
  <p>I think this is a little cleaner while still utilizing the suggestion to use <code>map</code>.</p>