title: How can I easily define more complex PartialFunctions in Scala?
body: <h2>PartialFunctions</h2>
  
  <p>In Scala, a <a href="http://www.scala-lang.org/api/current/index.html#scala.PartialFunction" rel="noreferrer"><code>PartialFunction</code></a> is, in short, a function that additionally defines an <code>isDefinedAt</code> method.</p>
  
  <p>It is easy to define partial functions with a series of <code>case</code> statement. A trivial example would be, e.g.:</p>
  
  <pre><code>scala&gt; val pf: PartialFunction[Int, Unit] = {
       | case 42 =&gt; ()
       | }
  pf: PartialFunction[Int,Unit] = &lt;function1&gt;
  
  scala&gt; pf.isDefinedAt(42)
  res0: Boolean = true
  
  scala&gt; pf.isDefinedAt(0) 
  res1: Boolean = false
  </code></pre>
  
  <p><code>isDefinedAt</code> is automatically generated from the list of <code>case</code>s defining the partial function.</p>
  
  <h2>Context</h2>
  
  <p>The Lift framework makes use of partial functions in many places, e.g. to define whether a request should be processed by Lift's engine or served directly from a file on disk, as is. and sometimes, I find myself wanting to write a <code>case</code> statement that matches all input parameters and only later decide if I want to return a value or not. This means that the initial series of <code>case</code>s is not enough any more to determine if my function is defined at a given value or not</p>
  
  <p>For instance, in Lift, I want to add a rule that all html and htm files are served directly, and that files with the “lift” extension should be processed. It would look easy to do something like this:</p>
  
  <pre><code>LiftRules.liftRequest.prepend {
    case Req(path, extension, tpe) =&gt; extension match {
      case "html" | "htm" =&gt; false
      case "lift" =&gt; true
    }
  }
  </code></pre>
  
  <p>Unfortunately, in this case, the compiler thinks that my partial function is defined everywhere, as the first <code>case</code> always matches. It's the nested <code>match</code> that may not match all incoming requests. And, is a request is not matched, a <code>MatchError</code> is thrown.</p>
  
  <h2>Question</h2>
  
  <p>Is there a simple way to make the compiler consider nested <code>match</code> statements when defining a partial function, or is the only way to do it to inline all nested conditionals like this?</p>
  
  <pre><code>LiftRules.liftRequest.prepend {
    case Req(path, extension, tpe) if extension == "html" || extension == "htm" =&gt; false
    case Req(path, extension, tpe) if extension == "lift" =&gt; true
  }
  </code></pre>
  
  <p>In this example, it's largely doable, but the readability is decreased, and I've faced cases where inlining all checks looks very ugly.</p>