Why can't upper-case letters be used for pattern matching for define values?

后端 未结 1 490
逝去的感伤
逝去的感伤 2021-01-18 02:34

Why can I use lower-case letters for names:

val (a, bC) = (1, 2)

(1, 2) match {
  case (a, bC) => ???
}

and can\'t use upper-case lette

相关标签:
1条回答
  • 2021-01-18 03:17

    Because the designers of Scala preferred to allow identifiers starting with upper-case letters to be used like this (and allowing both would be confusing):

    val A = 1
    
    2 match {
      case A => true
      case _ => false
    } // returns false, because 2 != A
    

    Note that with lower case you'll get

    val a = 1
    
    2 match {
      case a => true
      case _ => false
    } // returns true
    

    because case a binds a new variable called a.

    One very common case is

    val opt: Option[Int] = ...
    
    opt match {
      case None => ... // you really don't want None to be a new variable here
      case Some(a) => ...
    }
    
    0 讨论(0)
提交回复
热议问题