部分函数类型
在scala play框架中我看到了这段代码:
abstract class AnalyserInfo
case class ColumnC(typeName:String,fieldName:String) extends AnalyserInfo
case class TableC(typeName:String) extends AnalyserInfo
val asIs :PartialFunction[AnalyserInfo,String] = {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
与以下内容有什么区别:
val asIs: (AnaliserInfo)=>String = (info) => info match {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
有首选风格?为什么在第一种情况下可以省略 match 关键字?
感谢您的支持。
in scala play framework I seen this code:
abstract class AnalyserInfo
case class ColumnC(typeName:String,fieldName:String) extends AnalyserInfo
case class TableC(typeName:String) extends AnalyserInfo
val asIs :PartialFunction[AnalyserInfo,String] = {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
What is the difference with:
val asIs: (AnaliserInfo)=>String = (info) => info match {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
There is a preferred style? and why in the first case the match keyword can be omitted?
Thank you for the support.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
双=> Double
只是Function[Double, Double]
的简写。PartialFunction
继承自Function
但添加了一些方法。最重要的是,它添加了 isDefinedAt 方法,该方法允许您查询是否为某些参数定义了该函数。不匹配的
case
是定义部分函数的特殊语法,它会生成一个isDefinedAt
,为所有匹配的case 返回
。true
假设我们有一个返回 1/x 的函数,但仅对于 x 的正值,我们可以将其定义为:
或:
第二个版本的好处是我们可以检查该函数是否适用于某些参数:
此功能是例如,在 Scala 中用于实现 Actor 库,其中 Actor 可能仅使用某些类型的消息。
Double => Double
is just a shorthand forFunction[Double, Double]
.PartialFunction
inherits fromFunction
but adds a few methods. Most importantly, it adds the methodisDefinedAt
which allows you to query if the function is defined for some parameter.The
case
s without a match are a special syntax to define partial functions, which generates anisDefinedAt
that returnstrue
for all matchingcase
s.Say we have a function that returns 1/x, but only for positive values of x, we could it define as:
or as:
The second version has the benefit that we could check if the function is applicable to some parameter:
This feature is for example used in Scala to implement the actor library where an Actor might only consume certain types of messages.