Scala pattern matching with lowercase variable name

前端 未结 4 1258
没有蜡笔的小新
没有蜡笔的小新 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:21

    This is not specific to patterns with alternatives, and it is not a bug. An identifier that begins with a lowercase letter in a pattern represents a new variable that will be bound if the pattern matches.

    So, your example is equivalent to writing:

    x match {
       case MyValue1 | MyValue2 => println ("first match")
       case y | z => println ("second match")
    }
    

    You can work around this by using backticks:

    x match {
       case MyValue1 | MyValue2 => println ("first match")
       case `myValue1` | `myValue2` => println ("second match")
    }
    

提交回复
热议问题