Search code examples
scalapartialfunction

Empty partial function in Scala


It seems to me like the { case ... => ... } syntax for partial functions require at least one case:

scala> val pf: PartialFunction[String, String] = { case "a" => "b" } 
pf: PartialFunction[String,String] = <function1>

scala> val pf: PartialFunction[String, String] = { }                
<console>:5: error: type mismatch;
 found   : Unit
 required: PartialFunction[String,String]
       val pf: PartialFunction[String, String] = { }
                                                 ^

So, what's the best way to define an "empty" partial function? Is there a better way than "manually" overriding isDefinedAt and apply?


Solution

  • Map is a PartialFunction so you can do:

    val undefined: PartialFunction[Any, Nothing] = Map.empty