在Scala中清空部分函数
在我看来,像部分函数的{ case ... => ... }
语法至less需要一种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
更好的方法?
Map是一个PartialFunction,所以你可以这样做:
val undefined: PartialFunction[Any, Nothing] = Map.empty
从Scala 2.10开始,你可以使用:
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
正如@didierd在评论中所说,由于参数差异,单个实例可以覆盖所有可能的参数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
从每个人的窃取,一个可能的组合:
val undefined : PartialFunction[Any, Nothing] = {case _ if false => sys.error("undefined") }
我能想到的最短的一个:
{ case _ if false => "" }
一个解决scheme(这是更多的黑客),以确保案件从未如此: { case x if x != x => sys.error("unexpected match") }
简单的好奇心,为什么你需要这样的function?
知道计划在scala库中添加一个空的成员并查看它是如何实现可能是有趣的: https : //github.com/scala/scala/commit/6043a4a7ed5de0be2ca48e2e65504f56965259dc