Llew Vallis
Llew Vallis

Reputation: 337

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?

Upvotes: 5

Views: 240

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

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

Upvotes: 10

Related Questions