2
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?

user4992519
  • 335
  • 4
  • 11

2 Answers2

2

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
Marth
  • 23,920
  • 3
  • 60
  • 72
  • Is there a better way to do a double (or more)-variable assignment from a single line of space-delimited integers compared to the one in my post? – user4992519 Jun 14 '15 at 15:53
  • @user4992519 : I'm assuming you still want `S` to be uppercase ? – Marth Jun 14 '15 at 15:56
  • I don't believe there is, at least not using pattern matching (see [this question](http://stackoverflow.com/questions/12636972/how-to-pattern-match-into-an-uppercase-variable)). Why do you need `S` to be uppercase ? The [Scala Style Guide](http://docs.scala-lang.org/style/naming-conventions.html) say that values/variables should start by a lowercase letter. – Marth Jun 14 '15 at 16:08
  • Just for consistency's sake with other external programs I am cross-referencing with. Thanks though – user4992519 Jun 14 '15 at 16:13
1

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`   
}
dcastro
  • 66,540
  • 21
  • 145
  • 155