Scala Language Pattern Matching compiled as tableswitch or lookupswitch


The @switch annotation tells the compiler that the match statement can be replaced with a single tableswitch instruction at the bytecode level. This is a minor optimization that can remove unnecessary comparisons and variable loads during runtime.

The @switch annotation works only for matches against literal constants and final val identifiers. If the pattern match cannot be compiled as a tableswitch/lookupswitch, the compiler will raise a warning.

import annotation.switch

def suffix(i: Int) = (i: @switch) match {
  case 1 => "st"
  case 2 => "nd"
  case 3 => "rd"
  case _ => "th"

The results are the same as a normal pattern match:

scala> suffix(2)
res1: String = "2nd"

scala> suffix(4)
res2: String = "4th"

From the Scala Documentation (2.8+) – @switch:

An annotation to be applied to a match expression. If present, the compiler will verify that the match has been compiled to a tableswitch or lookupswitch, and issue an error if it instead compiles into a series of conditional expressions.

From the Java Specification: