Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't upper-case letters be used for pattern matching for define values?

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

like image 972
John Mullins Avatar asked Feb 05 '16 06:02

John Mullins


1 Answers

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) => ...
}
like image 139
Alexey Romanov Avatar answered Oct 25 '22 08:10

Alexey Romanov