title: Scope of variables inside scala’s case guard statement
body: <p>For lift development, I sometimes need to use <code>match</code>–<code>case</code> statements like the following. (Rewritten to plain scala for easier understanding.) One note to them: These are actually different partial functions, defined in different parts of the code, so it’s important that a case statement fails in or before the guard in order to have the other partial functions evaluated (if matching fails, that is).</p>
  
  <pre><code>// The incoming request
  case class Req(path: List[String], requestType: Int)
  
  // Does some heavy database action (not shown here)
  def findInDb(req: Req):Option[Int] = 
    if(req.path.length &gt; 3) Some(2) else None
  
  Req("a"::"b"::Nil, 3) match {
    case r@Req(`path` :: _ :: Nil, 3) if findInDb(r).isDefined =&gt;
      doSomethingWith(findInDb(r))
    case r@Req(`path` :: _ :: Nil, _) =&gt; doDefault
    case _ =&gt; doNothing
  }
  </code></pre>
  
  <p>Now, in order to know that the <code>case</code> statement succeeds, I must query the database with <code>findInDb</code> and check whether the result is valid. Afterwards, I must call it again to use the value.</p>
  
  <p>Doing something like</p>
  
  <pre><code>case r@Req(path, 3) if {val res = findInDb(r); res.isDefined} =&gt;
  </code></pre>
  
  <p>does not work because the scope of <code>res</code> is then limited to inside the braces.</p>
  
  <p>I can of course define a <code>var res = _</code> outside and assign to it, but I don’t feel well doing this.</p>
  
  <p>Is it by any means possible to declare a variable inside the guard? If it is possible to do <code>case r@Req(…)</code> why not <code>case r@Req() if res@(r.isDefined)</code>?</p>