I found that when using pattern matching with alternatives (for strings), Scala accepts variables starting with upper case (in the example below, MyValue1
and <
It is a feature. Stable identifiers beginning with an uppercase letter are treated like literals for the purpose of pattern matching, and lowercase identifiers are "assigned to" so you can use the matched value for something else.
You gave an example of it not making sense:
x match {
case myValue1 => println ("match")
case _ =>
}
But the sense is easy to see if we change that a little:
x match {
case MyValue1 => println("match")
case MyValue2 => println("match")
case other => println("no match: "+other)
}
Of course, one could use x
instead of other
above, but here are some examples where that would not be convenient:
(pattern findFirstIn text) {
// "group1" and "group2" have been extracted, so were not available before
case pattern(group1, group2) =>
// "other" is the result of an expression, which you'd have to repeat otherwise
case other =>
}
getAny match {
// Here "s" is a already a string, whereas "getAny" would have to be typecast
case s: String =>
// Here "i" is a already an int, whereas "getAny" would have to be typecase
case i: Int =>
}
So there are many reasons why it is convenient for pattern matching to assign the matched value to an identifier.
Now, though I think this is one of the greatest misfeatures of Scala, because it is so subtle and unique, the reasoning behind it is that, in the recommended Scala style, constants are camel cased starting with an uppercase letter, while methods and vals and vars (which are really methods too) are camel cased starting with lowercase letters. So constants are naturally treated as literals, while others are treated as assignable identifiers (which may shadow identifiers defined in an outer context).