为什么大写字母不能用于定义值的模式匹配? [英] Why can't upper-case letters be used for pattern matching for define values?

查看:50
本文介绍了为什么大写字母不能用于定义值的模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的名字可以使用小写字母:

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

我正在使用 scala-2.11.17

推荐答案

因为 Scala 的设计者更喜欢允许像这样使用以大写字母开头的标识符(并且允许两者都会混淆):

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

请注意,您会得到小写

val a = 1

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

因为case a 绑定了一个名为a 变量.

because case a binds a new variable called a.

一种非常常见的情况是

val opt: Option[Int] = ...

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

这篇关于为什么大写字母不能用于定义值的模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆