Scala中的空分部函数



在我看来,部分函数的{ 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] = { }
                                                 ^

那么,定义"空"偏函数的最佳方法是什么呢?有比"手动"覆盖isDefinedAtapply更好的方法吗?

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在评论中所说,由于参数差异,单个实例可以覆盖所有可能的参数类型。

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 => "" }

解决方案(更像是一种破解(是确保这种情况永远不会发生:{ case x if x != x => sys.error("unexpected match") }

单纯的好奇,你为什么需要这样的功能?

了解计划向scala库添加一个空成员,并了解它是如何实现的,可能会很有趣:https://github.com/scala/scala/commit/6043a4a7ed5de0be2ca48e2e65504f56965259dc

相关内容

  • 没有找到相关文章

最新更新