在我看来,部分函数的{ case ... => ... }
语法至少需要一个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] = { }
^
那么,定义“空”部分函数的最佳方法是什么?有没有比“手动”覆盖isDefinedAt
和apply
更好的方式?
答案 0 :(得分:52)
Map是PartialFunction,所以你可以这样做:
val undefined: PartialFunction[Any, Nothing] = Map.empty
答案 1 :(得分:39)
自Scala 2.10起,您可以使用:
val emptyPf = PartialFunction.empty[String, String]
答案 2 :(得分:8)
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
正如@didierd在评论中所说,由于参数差异,单个实例可以涵盖所有可能的参数类型。
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
答案 3 :(得分:6)
从每个人那里偷窃,可能是所有人的混合:
val undefined : PartialFunction[Any, Nothing] = {case _ if false =>
sys.error("undefined")
}
答案 4 :(得分:5)
我能想到的最短的一个:
{ case _ if false => "" }
答案 5 :(得分:4)
解决方案(更像是黑客攻击)是为了确保案例永远不会成立:{ case x if x != x => sys.error("unexpected match") }
简单的好奇心,为什么你需要这样的功能?
答案 6 :(得分:3)
知道计划在scala库中添加一个空成员并查看其实现方式可能会很有趣: https://github.com/scala/scala/commit/6043a4a7ed5de0be2ca48e2e65504f56965259dc