Error: Not found: Value S (Scala)

Error: Not found: Value S (Scala)

val Array(k,s) = readLine.split(" ").map(_.toInt)

这段代码工作正常。但不是这个:

val Array(k,S) = readLine.split(" ").map(_.toInt)

这里大写"s"报错:error: not found: value S

这是怎么回事?

当您使用 val Array(k,s) = ... 创建 ks 标识符时,您正在使用模式匹配来定义它们。

来自Scala Specifications1.1标识符):

The rules for pattern matching further distinguish between variable identifiers, which start with a lower case letter, and constant identifiers, which do not.

也就是说,当您说 val Array(k,S) = ... 时,您实际上是在将 S 与常量进行匹配。由于您没有定义 S,Scala 报告 error: not found: value S.


请注意,如果定义了常量,Scala 将抛出一个 MatchError,但它仍然找不到匹配项:

scala> val S = 3
S: Int = 3

scala> val Array(k, S) = Array(1, 3)
k: Int = 1

scala> val Array(k, S) = Array(1, 4)
scala.MatchError: [I@813ab53 (of class [I)
  ... 33 elided

使用提取器时,以小写字符开头的符号将被解释为保存提取值的变量。另一方面,以大写字符开头的符号用于指代在外部作用域中声明的 variables/values。

另一个例子:

val X = 2

something match {
  case (X, y) => // matches if `something` is a pair whose first member is 2, and assigns the second member to `y`
  case (x, y) => // matches if `something` is a pair, and extracts both `x` and `y`   
}