Thomas
Thomas

Reputation: 6196

Understaning how function literals created with braces work

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 => ?

Upvotes: 0

Views: 67

Answers (1)

Mario Galic
Mario Galic

Reputation: 48410

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.

Upvotes: 5

Related Questions