Scala 中如何省略匹配词? [英] How is a match word omitted in Scala?
问题描述
在 Scala 中,你可以这样做
list.filter { item =>项目匹配{case Some(foo) =>foo.bar >0}}
但是你也可以通过省略match
来更快地完成:
list.filter {case Some(foo) =>foo.bar >0}
Scala 如何支持此功能?这是 2.9 的新功能吗?我一直在寻找它,我可以弄清楚是什么使这成为可能.它只是 Scala 编译器的一部分吗?
语言规范解决了第 8.5 节中的问题.相关部分:
<块引用>匿名函数可以由一系列 case 定义
{ case p1 =>b1 ...情况pn =>十亿 }
<块引用>
如果预期的类型是 scala.Functionk[S1, ..., Sk, R]
,则表达式为等价于匿名函数:
(x1 : S1, ..., xk : Sk) =>(x1, ..., xk) 匹配 {情况p1=>b1 ...情况pn =>十亿}
<块引用>
如果预期类型是 scala.PartialFunction[S, R]
,则表达式被取为等价于下面的实例创建表达式:
new scala.PartialFunction[S, T ] {def apply(x: S): T = x match {情况p1=>b1 ...情况pn =>十亿}def isDefinedAt(x: S): Boolean = {情况p1=>真... case pn =>真的案例_ =>错误的}}
因此将表达式键入为 PartialFunction
或 Function
会影响表达式的编译方式.
Also trait PartialFunction [-A, +B] extends (A) ⇒ B
所以一个部分函数 PartialFunction[A,B]
也是一个 Function[A,B]
.
In Scala, you can do
list.filter { item =>
item match {
case Some(foo) => foo.bar > 0
}
}
But you can also do the quicker way by omitting match
:
list.filter {
case Some(foo) => foo.bar > 0
}
How is this supported in Scala? Is this new in 2.9? I have been looking for it, and I can figure out what makes this possible. Is it just part of the Scala compiler?
The language specification addresses that in section 8.5. The relevant portions:
An anonymous function can be defined by a sequence of cases
{ case p1 => b1 ... case pn => bn }
If the expected type is
scala.Functionk[S1, ..., Sk, R]
, the expression is taken to be equivalent to the anonymous function:
(x1 : S1, ..., xk : Sk) => (x1, ..., xk) match {
case p1 => b1 ... case pn => bn
}
If the expected type is
scala.PartialFunction[S, R]
, the expression is taken to be equivalent to the following instance creation expression:
new scala.PartialFunction[S, T ] {
def apply(x: S): T = x match {
case p1 => b1 ... case pn => bn
}
def isDefinedAt(x: S): Boolean = {
case p1 => true ... case pn => true
case _ => false
}
}
So typing the expression as PartialFunction
or a Function
influences how the expression is compiled.
Also trait PartialFunction [-A, +B] extends (A) ⇒ B
so a partial function PartialFunction[A,B]
is also a Function[A,B]
.
这篇关于Scala 中如何省略匹配词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!