1

When I use a variable starting with caps for pattern matching in Scala, it gives a compile error. This is a style issue, I don't understand why is this a compile error.

The following snippet reports "error: not found: value Name".

val pair = Tuple2(1,"abc") val (key, Name) = pair

However, the following works:

val pair = Tuple2(1,"abc") val (key, name) = pair

Sharvanath
  • 457
  • 4
  • 15
  • possible duplicate of [How to pattern match into an uppercase variable?](http://stackoverflow.com/questions/12636972/how-to-pattern-match-into-an-uppercase-variable) – Chris Martin Oct 11 '14 at 22:52

2 Answers2

4

Pattern expressions use the case of each identifier's first letter to determine whether it's a new val declaration or a reference to an existing val. This is an ugly quirk of Scala's syntax (though if you stick to the established naming conventions, you don't run into it).

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
0

It's not style, albeit stylish.

scala> val pair = Tuple2(1,"abc"); val (key, Name) = pair
<console>:7: error: not found: value Name
       val pair = Tuple2(1,"abc"); val (key, Name) = pair
                                             ^

scala> val pair = Tuple2(1,"abc"); val Name = "abc" ; val (key, Name) = pair
pair: (Int, String) = (1,abc)
Name: String = abc
key: Int = 1

A pattern is a pattern:

scala> (1,"abc") match { case (key, Name) => key }
res0: Int = 1

scala> (1,"abc") match { case (key, Fame) => key }
<console>:11: error: not found: value Fame
              (1,"abc") match { case (key, Fame) => key }
                                           ^

But this is kind of a good one, for some reason.

http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#variable-patterns

som-snytt
  • 39,429
  • 2
  • 47
  • 129