PartialFunction 和 MatchError [英] PartialFunction and MatchError

查看:36
本文介绍了PartialFunction 和 MatchError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are two ways to define PF: 1) with literal case {} syntax and 2) as explicit class. I need the following function throw a MatchError, but in the second case that doesn't happen.

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,它不应该被编译器隐式调用吗?

Should i, in the seconds case, manually call isDefinedAt, shouldn't it be called implicitly by the compiler?

推荐答案

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

You will have to call isDefinedAt manually in your apply method:

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 语言规范中所述,您的第一个定义将扩展为以下内容:

If you want to avoid this code, you can simply use the first way to define your partial function. It is syntactic sugar and will result in a valid definition of both isDefinedAt and apply. As described in the Scala language specification, your first definition will expand to the following:

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

这篇关于PartialFunction 和 MatchError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆