Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala syntax strangeness with :: and requiring lower case

Tags:

syntax

scala

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

like image 546
da_steve101 Avatar asked Jul 28 '15 08:07

da_steve101


2 Answers

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:

  • Why does pattern matching in Scala not work with variables?
  • Scala pattern matching with lowercase variable name
  • How to pattern match into an uppercase variable?
like image 168
Chris Martin Avatar answered Sep 29 '22 09:09

Chris Martin


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.

like image 35
mikej Avatar answered Sep 29 '22 10:09

mikej