首页 > 解决方案 > 理解用大括号创建的函数字面量是如何工作的

问题描述

从这个答案引用另一个问题

“Scala 具有函数和部分函数文字的语法。它看起来像这样”:

{
    case pattern if guard => statements
    case pattern => statements
}

它是如何工作的,在什么情况下可以使用大括号{}而不是箭头创建函数文字=>

标签: scala

解决方案


模式匹配匿名函数

{ case pattern => value }

相当于

x => x match { case pattern => value }

并根据预期的类型变为PartialFunctionor 或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 中的模式匹配匿名函数与数学中的分段函数定义之间的相似性

在数学中,分段定义函数(也称为分段函数、混合函数或按情况定义)是由多个子函数定义的函数,其中每个子函数适用于域中的不同区间。


推荐阅读