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?
“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.
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.
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...") }
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.
You don't want to create a PartialFunction
and have a function call each time for such a fundamental operation.
Tail calls in match
become non-tail-calls in matchy
.
This is exactly the kind of megamorphic call JITs have trouble inlining. matchy
could be made explicitly @inline
though.
In general, you lose a lot of optimization opportunities.
Probably more reasons I am missing...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With