Empty partial function in Scala

It seems to me that the syntax { case ... => ... } for partial functions requires 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 is the best way to define an "empty" partial function? Is there a better way than manually overriding isDefinedAt and apply ?

+47
scala partialfunction
Aug 25 2018-11-11T00:
source share
7 answers

A map is a PartialFunction, so you can:

 val undefined: PartialFunction[Any, Nothing] = Map.empty 
+49
Aug 26 2018-11-11T00:
source share

Since Scala 2.10 you can use:

 val emptyPf = PartialFunction.empty[String, String] 
+28
Aug 31 '13 at 8:51
source share
 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 points out in the comments, due to variances of arguments, one instance can cover all possible types of arguments.

 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 
+8
Aug 25 '11 at 10:50
source share

Theft from everyone, a possible combination of all this:

 val undefined : PartialFunction[Any, Nothing] = {case _ if false => sys.error("undefined") } 
+6
Aug 25 2018-11-11T00:
source share

The shortest I can think of:

 { case _ if false => "" } 
+5
Aug 25 '11 at 12:03
source share

The solution (this is more likely a hack) is to make sure that the case is never true: { case x if x != x => sys.error("unexpected match") }

Just curiosity, why is such a function needed?

+4
Aug 25 2018-11-11T00:
source share

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

+3
Aug 30 '11 at 9:45 a.m.
source share



All Articles