Reputation: 337
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
Reputation: 170745
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...
Upvotes: 10