Pattern match for variable in scope (Scala)

后端 未结 2 1502
猫巷女王i
猫巷女王i 2021-01-05 16:16

In the following code

val x = 5
val y = 4 match {
  case x => true
  case _ => false
}

the value y is true. Scala interp

相关标签:
2条回答
  • 2021-01-05 16:32

    Backticking the variable indicates to bind a scoped variable:

    val x = 5
    val y = 4 match { case `x` => true; case _ => false }
    

    returns false.

    Alternatively, if a variable starts with an uppercase letter, it binds to a scoped variable without backticking.

    0 讨论(0)
  • 2021-01-05 16:45

    Invoking the least astonishment principle, I will simply do:

    val x = 5
    val y = 4 match {
      case z if z == x => true
      case _ => false
    }
    
    0 讨论(0)
提交回复
热议问题