da_steve101
da_steve101

Reputation: 283

Scala syntax strangeness with :: and requiring lower case

is this supposed to happen?

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
           ^

It appears to be case sensitive. Bug or 'feature'?

Upvotes: 6

Views: 176

Answers (2)

Chris Martin
Chris Martin

Reputation: 30746

It is case-sensitive. In a match pattern, an identifier beginning with a capital letter (or quoted by backticks) is treated as a reference to a defined value, not as a new binding.

This catches a lot of people by surprise, and it isn't entirely obvious from reading the Scala language specification. The most relevant bits are “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.

... and “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.

Related questions:

Upvotes: 5

mikej
mikej

Reputation: 66283

Feature :)

:: is a form of pattern matching. In Scala, variables beginning with lowercase are used for variables that should be bound by the match. Variables starting with uppercase (or enclosed in backticks) are used for existing variables that are used as part of the pattern to match.

Upvotes: 2

Related Questions