val Array(k,s) = readLine.split(" ").map(_.toInt)
This code works fine. But not this:
val Array(k,S) = readLine.split(" ").map(_.toInt)
Capitalizing "s" here gives me an error: error: not found: value S
What is going on?
val Array(k,s) = readLine.split(" ").map(_.toInt)
This code works fine. But not this:
val Array(k,S) = readLine.split(" ").map(_.toInt)
Capitalizing "s" here gives me an error: error: not found: value S
What is going on?
When you are creating the k
and s
identifiers with val Array(k,s) = ...
, you are using pattern matching to define them.
From the Scala Specifications (1.1 Identifiers):
The rules for pattern matching further distinguish between variable identifiers, which start with a lower case letter, and constant identifiers, which do not.
That is, when you say val Array(k,S) = ...
, you're actually matching S
against a constant. Since you have no S
defined, Scala reports error: not found: value S
.
Note that Scala will throw a MatchError
if the constant is defined but it still cannot find a match :
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
When using extractors, symbols that begin with a lower case character will be interpreted as a variable to hold an extracted value. On the other hand, symbols that begin with an upper case character are used to refer to variables/values declared in an outer scope.
Another example:
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`
}