0

Quoting from this answer to a different question

"Scala has a syntax for function and partial function literals. It looks like this":

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

How does it work and under what circumstances can you create a function literal with brace {} instead of the arrow => ?

Thomas
  • 6,032
  • 6
  • 41
  • 79

1 Answers1

5

Pattern Matching Anonymous Function

{ case pattern => value }

is equivalent to

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

and depending on the expected type becomes either PartialFunction or FunctionN.

For example,

val f: Int => String = { case x => "" }

becomes

val f: Int => String = (x: Int) => x match { case x => "" }

which is equivalent to

val f: Function1[Int, String] = new Function1[Int, String] {
  def apply(x: Int): String = x match {
    case x => ""
  }
}

because the expected type is Int => String

whilst

val f: PartialFunction[Int, String] = { case x => "" }

becomes

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
  }
}

because the expected type is PartialFunction[Int, String].

Therefore pattern matching anonymous function expression with braces can be used wherever the corresponding expanded versions would be accepted according to the expected type.


As a side note, consider the similarity between pattern matching anonymous functions in Scala and piecewise function definition in mathematics

In mathematics, a piecewise-defined function (also called a piecewise function, a hybrid function, or definition by cases) is a function defined by multiple sub-functions, where each sub-function applies to a different interval in the domain.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • I'd just like to add that `{ case (x, y) => foo }` can also be a function taking two arguments instead of a single 2-tuple. – user Mar 31 '21 at 17:52