- 修订后 -
嗯,我不知道我看到的差异,斯卡拉2.9.1.RC3,
val f: PartialFunction[Int, Int] = { case 2 => 3 }
f.isDefinedAt(1) // evaluates to false
f.isDefinedAt(2) // evaluates to true
f(1) // match error
val g: PartialFunction[Int, Int] = x => x match { case 2 => 3 }
g.isDefinedAt(1) // evaluates to false
g.isDefinedAt(2) // evaluates to true
g(1) // match error
看来f
和g
行为都一模一样与PartialFunctions
相同。
这里是另一个例子展示了等价:更有意思的
Seq(1, "a").collect(x => x match { case s: String => s }) // evaluates to Seq(a)
:
// this compiles
val g: PartialFunction[Int, Int] = (x: Int) => {x match { case 2 => 3 }}
// this fails; found Function[Int, Int], required PartialFunction[Int, Int]
val g: PartialFunction[Int, Int] = (x: Int) => {(); x match { case 2 => 3 }}
所以这是在编译器级别的一些特殊套管x => x match {...}
,只是{...}
之间的转换。
更新。在阅读语言规范后,这对我来说似乎是一个错误。我在错误跟踪器中提交了SI-4940。
事实上,你的第一个变种是无效的。 item没有定义(应该是,它并不意味着列表中的一个元素)。过滤器期望一个函数,你必须编写list.filter {item => item match ...这不仅仅是匹配消失。 –
@didierd,我编辑了这个问题来解决你的问题,因为我认为这里仍然有一个有趣的问题。 –
@kipton感谢您的更新。 –