7

A/a case, not case case.

Apparently case a matches anything and binds it to the name a, while case A looks for an A variable and matches anything == considers equal to A. This came as quite a surprise to me; while I know Scala is case sensitive, I never expected identifier case to affect the parsing rules.

Is it common for Scala's syntax to care about the case of identifiers, or is there only a small number of contexts in which this happens? If there's only a small number of such contexts, what are they? I couldn't find anything on Google; all I got were results about pattern matching.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    Actually, I believe that's the only one, but I'll leave answering to someone who knows the spec better than me. – Jörg W Mittag Mar 14 '17 at 23:41
  • I think you're looking for [*stable identifier patterns*](http://www.scala-lang.org/files/archive/spec/2.12/08-pattern-matching.html#stable-identifier-patterns) – Bergi Mar 14 '17 at 23:50
  • 1
    @Bergi: I actually linked that in the question already, although with the death of link underlining, it might be hard to notice. – user2357112 Mar 14 '17 at 23:56

1 Answers1

4

There is one more that is similar in nature, called a type pattern. In a type pattern, a simple identifier that starts with a lower case letter is a type variable, and all others are attempt to match actual types (except _).

For example:

val a: Any = List(1, 2, 3)
val c = 1

// z is a type variable
a match { case b: List[z] => a }

// Type match on `Int`
a match { case b: List[Int] => a }

// type match on the singleton c.type (not a simple lower case identifier)
// (doesn't actually compile because c.type will never conform)
a match { case b: List[c.type] => a }

Type matching like the the first example is lesser-known because, well, it's hardly used.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • [Here](http://stackoverflow.com/a/7318089/2292812) is a nice example of type variables in action. – Michael Zajac Mar 15 '17 at 00:30
  • I was really hoping there wouldn't be more examples, but at least the two examples follow a consistent pattern. Do you know if those are the only examples, as of 2.12? (Not accepting because I don't want to discourage further answers or pin this to the top, especially if the language changes and more case significance is added.) – user2357112 Mar 15 '17 at 00:54
  • @user2357112 I can only say with 99.99% certainty, because who knows if theirs some strange bug no one has ever run into, but these two similar cases are the only ones mentioned in the spec. I'd be interested to see if anyone comes up with something else, though. – Michael Zajac Mar 15 '17 at 02:12