Type variable can only be introduced in match if it's lower-case?

generics, scala

Solution

You can see the same thing with value variables in patterns:

scala> Some(0) match { case A => 0 }
<console>:8: error: not found: value A
              Some(0) match { case A => 0 }
                                   ^

scala> Some(0) match { case a => 0 }
res1: Int = 0

If you want to introduce a variable (either at the value or type level) in a pattern, you have to use a lower case identifier—there's simply no way to introduce an upper case variable. Note that going the other direction is possible—if you want to match against the value of a lower case variable, you can surround it with back quotes.

From the language specification (discussing a change introduced in 2.3):

The syntax of types in patterns has been refined (§8.2). Scala now distinguishes be- tween type variables (starting with a lower case letter) and types as type arguments in patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased.

So no, not a bug, although it's arguably a pretty confusing language design decision.

Problem

While trying to understand some code, I've run into strange behaviour and reduced it to this: Introducing type parameter in a match doesn't work: ``` scala> Some(0) match { case _: Some[A] => 0 } <console>:8: error: not found: type A Some(0) match { case _: Some[A] => 0 } ^ ``` However, if I make it lower-case, it does: ``` scala> Some(0) match { case _: Some[a] => 0 } res2: Int = 0 ``` Is this a bug in Scala or is there an explanation I am missing?

Original source