Question

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?

Was it helpful?

Solution

Map is a PartialFunction so you can do:

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

OTHER TIPS

Since Scala 2.10 you can use:

val emptyPf = PartialFunction.empty[String, String]
scala> def pfEmpty[A, B] = new PartialFunction[A, B] {
     |   def apply(a: A): B = sys.error("Not supported")
     |   def isDefinedAt(a: A) = false
     | }
pfEmpty: [A, B]=> java.lang.Object with PartialFunction[A,B]

scala> val f = pfEmpty[String, String]
f: java.lang.Object with PartialFunction[String,String] = <function1>

scala> f.lift
res26: (String) => Option[String] = <function1>

scala> res26("Hola")
res27: Option[String] = None

As @didierd said in the comments, due to argument variances, a single instance can cover all possible argument types.

scala> object Undefined extends PartialFunction[Any, Nothing] {
     |   def isDefinedAt(a: Any) = false
     |   def apply(a: Any): Nothing = sys.error("undefined")
     | }
defined module Undefined

scala> val f: PartialFunction[String, String] = Undefined
f: PartialFunction[String,String] = <function1>

scala> f.lift apply "Hola"
res29: Option[String] = None

Stealing from everyone, a possible mix of it all :

val undefined : PartialFunction[Any, Nothing] = {case _ if false =>
  sys.error("undefined")
}

Shortest one I can think of:

{ case _ if false => "" }

A solution (which is more a hack) is to ensure that the case is never true: { case x if x != x => sys.error("unexpected match") }

Simple curiosity, why do you need such a function?

It may be interesting to know that it is planned to add an empty member to the scala library and to see how it is implemented: https://github.com/scala/scala/commit/6043a4a7ed5de0be2ca48e2e65504f56965259dc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top