rapt rapt - 2 months ago 8
Scala Question

Pattern matching in Scala for String and Int

Why does pattern matching in Scala work for

String
and
AnyVal
s such as
Int
?

Usually we see things like
Case classes
or
Extractors
...

Answer

Extractors and case classes are used just for two of 13 kinds of patterns in Scala, "Extractor patterns" and "Constructor patterns" respectively. You can't use Int or String in this kind of pattern (case String(x)). But you can use them in other kinds:

  1. Typed patterns, as in case x: String. In that case there is nothing special about String, you can do the same with any class (but there is something special about Int and other primitives: case x: Int actually checks if the received object is a java.lang.Integer in most cases).

  2. Literal patterns, as in case 0 or case "". Again, nothing special about strings, this works for all literals.