rapt rapt - 1 year ago 109
Scala Question

Pattern matching in Scala for String and Int

Why does pattern matching in Scala work for

s such as

Usually we see things like
Case classes

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download