【问题标题】:PartialFunction and MatchErrorPartialFunction 和 MatchError
【发布时间】:2013-07-23 09:23:01
【问题描述】:

定义 PF 有两种方法:1)使用文字 case {} 语法和 2)作为显式类。我需要下面的函数抛出一个 MatchError,但在第二种情况下不会发生。

1) 带外壳

val test: PartialFunction[Int, String] =  {
  case x if x > 100 => x.toString
}

2) 作为类

val test = new PartialFunction[Int, String] {
  def isDefinedAt(x: Int) = x > 100
  def apply(x: Int) = x.toString
}

在秒的情况下,我应该手动调用isDefinedAt,不应该被编译器隐式调用吗?

【问题讨论】:

    标签: scala partialfunction


    【解决方案1】:

    您必须在 apply 方法中手动调用 isDefinedAt

    val test = new PartialFunction[Int, String] {
      def isDefinedAt(x: Int) = x > 100
      def apply(x: Int) = if(isDefinedAt(x)) x.toString else throw new MatchError(x)
    }
    

    如果你想避免这段代码,你可以简单地使用第一种方法来定义你的偏函数。它是语法糖,将导致isDefinedAtapply 的有效定义。如Scala language specification 中所述,您的第一个定义将扩展为以下内容:

    val test = new scala.PartialFunction[Int, String] {
      def apply(x: Int): String = x match {
        case x if x > 100 => x.toString
      }
      def isDefinedAt(x: Int): Boolean = {
        case case x if x > 100 => true
        case _ => false
      }
    }
    

    【讨论】:

      【解决方案2】:

      isDefinedAt 不是守卫:无论何时调用PartialFunction,它都不会被检查。

      在您的第一种情况下,MatchError 发生是因为模式匹配失败。实际上,您可以在Scala Specification 的§8.5 中了解Partialfunction 在第一种情况下是如何构建的。

      在第二种情况下,为所有x 定义了apply,然后您对isDefinedAt 的定义无效。

      【讨论】:

        猜你喜欢
        • 2017-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多