Scala pattern matching with lowercase variable name

前端 未结 4 1253
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 08:17

I found that when using pattern matching with alternatives (for strings), Scala accepts variables starting with upper case (in the example below, MyValue1 and <

4条回答
  •  自闭症患者
    2020-11-30 08:41

    What's happening here is that myValue1 and myValue2 are being treated as variable identifiers (i.e., the definition of new variables that are bound to the value being matched), whereas MyValue1 and MyValue2 are treated as stable identifiers that refer to values declared earlier. In a pattern match case, variable identifiers must start with a lower case letter, hence why the first case behaves intuitively. See section 8.1 of the Scala Language Specification (http://www.scala-lang.org/docu/files/ScalaReference.pdf) for exact details.

    Altering your example slightly, you can see the variable identifier:

    scala> x match {
     | case MyValue1 | MyValue2 => println ("first match")
     | case myValue1 => println (myValue1)
     | }
    test
    

提交回复
热议问题