Reputation: 420951
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
?
Upvotes: 55
Views: 7346
Reputation: 27677
Since Scala 2.10 you can use:
val emptyPf = PartialFunction.empty[String, String]
Upvotes: 51
Reputation: 24759
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
Upvotes: 3
Reputation: 3855
Map is a PartialFunction so you can do:
val undefined: PartialFunction[Any, Nothing] = Map.empty
Upvotes: 60
Reputation: 29528
Stealing from everyone, a possible mix of it all :
val undefined : PartialFunction[Any, Nothing] = {case _ if false =>
sys.error("undefined")
}
Upvotes: 6
Reputation: 92026
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
Upvotes: 8
Reputation: 24759
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?
Upvotes: 4