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

荒凉一梦 提交于 2019-12-30 19:48:11

问题


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) => ...
}


来源:https://stackoverflow.com/questions/35217913/why-cant-upper-case-letters-be-used-for-pattern-matching-for-define-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!