Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is match a keyword and not a function in Scala?

I don't see why Scala has match defined as a keyword instead of a function. It could be defined through implicits (like ArrowAssoc). For example, consider the following.

  implicit class Matchy[A](a: A) {

    def matchy[T](pf: PartialFunction[A, T]): T = pf(a)
  }

  val myVar = 10
  val myString = myVar matchy {
    case 5 => "five"
    case 10 => "ten"
    case x => x.toString
  }

  println(myString) // Prints "ten".

This would free up match as a variable name and hint to the fact that case can be used outside of match blocks.

So why does Scala define match as a keyword?

like image 237
Llew Vallis Avatar asked Sep 25 '17 04:09

Llew Vallis


People also ask

What does match mean in Scala?

“match” is always defined in Scala's root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched.

What is match expression?

A match expression has a scrutinee expression, which is the value to compare to the patterns. The scrutinee expression and the patterns must have the same type. A match behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.

How do you use match function in Scala?

Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }

How do you write a match case in Scala?

Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching. First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional.


1 Answers

  1. You don't want to create a PartialFunction and have a function call each time for such a fundamental operation.

  2. Tail calls in match become non-tail-calls in matchy.

  3. This is exactly the kind of megamorphic call JITs have trouble inlining. matchy could be made explicitly @inline though.

  4. In general, you lose a lot of optimization opportunities.

Probably more reasons I am missing...

like image 77
Alexey Romanov Avatar answered Sep 21 '22 15:09

Alexey Romanov