scala - 理解用大括号创建的函数字面量是如何工作的
问题描述
“Scala 具有函数和部分函数文字的语法。它看起来像这样”:
{
case pattern if guard => statements
case pattern => statements
}
它是如何工作的,在什么情况下可以使用大括号{}
而不是箭头创建函数文字=>
?
解决方案
{ case pattern => value }
相当于
x => x match { case pattern => value }
并根据预期的类型变为PartialFunction
or 或FunctionN
。
例如,
val f: Int => String = { case x => "" }
变成
val f: Int => String = (x: Int) => x match { case x => "" }
这相当于
val f: Function1[Int, String] = new Function1[Int, String] {
def apply(x: Int): String = x match {
case x => ""
}
}
因为预期的类型是Int => String
同时
val f: PartialFunction[Int, String] = { case x => "" }
变成
val f: PartialFunction[Int, String] = new PartialFunction[Int, String[] {
def apply(x: Int): String = x match {
case x => ""
}
def isDefinedAt(x: Int): Boolean = {
case x => true
case _ => false
}
}
因为预期的类型是PartialFunction[Int, String]
.
因此,只要根据预期类型接受相应的扩展版本,就可以使用带有大括号的模式匹配匿名函数表达式。
作为旁注,请考虑 Scala 中的模式匹配匿名函数与数学中的分段函数定义之间的相似性
在数学中,分段定义函数(也称为分段函数、混合函数或按情况定义)是由多个子函数定义的函数,其中每个子函数适用于域中的不同区间。
推荐阅读
- spring - 将zuul路由重定向到serviceId主机
- c++ - std::mutex :: 当获得锁的线程被杀死时,对于 std::mutex 锁,其他等待线程会发生什么
- wordpress - wordpress 编辑器中的卡纳达语文本
- apache-camel - 无法创建路由,因为在注册表中找不到类型为:org.apache.camel.Processor 的 Processor1 的 bean
- python - 第 9 行的块标记无效:“静态”,应为“结束块”。您是否忘记注册或加载此标签?
- sql - 为什么执行时间等于0ms?
- java - Spring 安全 webjars 在子页面上不起作用
- ruby-on-rails - 为什么黄瓜找不到我的测试场景
- clojure - 如何在 Datalog/DataScript/Datomic 上对包括缺少属性的实体的值求和
- javascript - 找出一个字符串在一组字符串中变得唯一之前需要多少