How does scala deal with match
ing? Is it just syntax sugar that gets transformed into compiler branches at bytecode level or some clever trick hidden under the covers?
Asked
Active
Viewed 232 times
2

flavian
- 28,161
- 11
- 65
- 105
-
2Similar: http://stackoverflow.com/questions/754166/how-is-pattern-matching-in-scala-implemented-at-bytecode-level – Alex Yarmula Apr 10 '13 at 22:04
-
While that old question is clearly relevant and detailed, be aware that pattern matching code generation has been rewritten and significantly improved for 2.10. E.g., the possibility of exponential (code) space for certain kinds of pattern nesting has been eliminated. ALso I understand many bugs involving pattern matching when using extractors (instead of case classes) have been fixed over the years. So the answer from four years ago might contain significant inaccuracies for the current compiler. – Randall Schulz Apr 10 '13 at 23:15
1 Answers
3
Matching integral values (e.g., Int, Char) against constants is generally translated into a TableSwitch (O(1) lookup time through indexing an array) or a LookUpSwitch (O(log n) lookup time through binary search) bytecode instruction. This also remains the case if you have a variable pattern or wildcard pattern as a catch-all branch.
You can use the @switch annotation to ensure that this actually happens.
For non-integral values, the available optimizations are somewhat more limited; however, as far as I understand the compiler code, the compiler will at least check for common subconditions (which it remembers) and shared prefixes.

Reimer Behrends
- 8,600
- 15
- 19