Scala 语法奇怪与 :: 和要求小写
Scala syntax strangeness with :: and requiring lower case
这是应该发生的吗?
scala> val myList = List(42)
myList: List[Int] = List(42)
scala> val s2 :: Nil = myList
s2: Int = 42
scala> val S2 :: Nil = myList
<console>:8: error: not found: value S2
val S2 :: Nil = myList
^
它似乎区分大小写。错误或 'feature'?
区分大小写。在匹配模式中,以大写字母(或反引号引起来)开头的标识符被视为对已定义值的引用,而不是新绑定。
这让很多人大吃一惊,阅读 Scala 语言规范时也不是很明显。最相关的位是“variable patterns”...
A variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value.
...和“stable identifier patterns”:
To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter.
相关问题:
- Why does pattern matching in Scala not work with variables?
- Scala pattern matching with lowercase variable name
- How to pattern match into an uppercase variable?
功能:)
::
是模式匹配的一种形式。在 Scala 中,以小写字母开头的变量用于应该被匹配绑定的变量。以大写字母开头(或包含在反引号中)的变量用于 现有 变量,这些变量用作要匹配的模式的一部分。
这是应该发生的吗?
scala> val myList = List(42)
myList: List[Int] = List(42)
scala> val s2 :: Nil = myList
s2: Int = 42
scala> val S2 :: Nil = myList
<console>:8: error: not found: value S2
val S2 :: Nil = myList
^
它似乎区分大小写。错误或 'feature'?
区分大小写。在匹配模式中,以大写字母(或反引号引起来)开头的标识符被视为对已定义值的引用,而不是新绑定。
这让很多人大吃一惊,阅读 Scala 语言规范时也不是很明显。最相关的位是“variable patterns”...
A variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value.
...和“stable identifier patterns”:
To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter.
相关问题:
- Why does pattern matching in Scala not work with variables?
- Scala pattern matching with lowercase variable name
- How to pattern match into an uppercase variable?
功能:)
::
是模式匹配的一种形式。在 Scala 中,以小写字母开头的变量用于应该被匹配绑定的变量。以大写字母开头(或包含在反引号中)的变量用于 现有 变量,这些变量用作要匹配的模式的一部分。