Scala syntactic weirdness with :: and lowercase need

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 seems to be case sensitive. Error or "function"?

+6
source share
2 answers

It is case sensitive. In a matching pattern, an identifier starting with a capital letter (or quoted in reverse steps) is considered as a reference to a specific value, and not as a new binding.

This surprises many people, and it is not entirely obvious from reading the Scala language specification. The most important bits are " variable templates " ...

The variable x pattern is a simple identifier starting with a lowercase letter. It matches any value and binds the variable name to that value.

... and stable id patterns :

To eliminate syntax matches with a variable pattern, a stable identifier pattern may not be a simple name, starting with a lowercase letter.

Related questions:

+5
source

Function:)

:: is a pattern matching pattern. In Scala, variables starting with lowercase are used for variables that must be matched. Variables starting with uppercase (or enclosed in backticks) are used for existing variables that are used as part of the template for matching.

+2
source

All Articles