Why can't upper-case letters be used for patte

2020-04-04 05:30发布

问题:

Why can I use lower-case letters for names:

val (a, bC) = (1, 2)

(1, 2) match {
  case (a, bC) => ???
}

and can't use upper-case letters:

/* compile errors: not found: value A, BC  */
val (A, BC) = (1, 2)

/* compile errors: not found: value A, BC  */
(1, 2) match {
  case (A, BC) => ???
}

I'm using scala-2.11.17

回答1:

Because the designers of Scala preferred to allow identifiers starting with upper-case letters to be used like this (and allowing both would be confusing):

val A = 1

2 match {
  case A => true
  case _ => false
} // returns false, because 2 != A

Note that with lower case you'll get

val a = 1

2 match {
  case a => true
  case _ => false
} // returns true

because case a binds a new variable called a.

One very common case is

val opt: Option[Int] = ...

opt match {
  case None => ... // you really don't want None to be a new variable here
  case Some(a) => ...
}