在scala模式匹配中,可变模式可疑的阴影是什么?
收藏

当我在Intellij中键入以下代码时,它会用警告“变量模式可疑阴影”突出显示匹配项中的x。

val x = "some value"
"test" match {
  case x =>
}

它建议我将其更改为:

val x = "some value"
"test" match {
  case `x` => //note backticks
}

什么是可疑阴影?反引号是做什么的?

最佳答案

case x

creates a variable named x, which would match everything and since a variable with the same name already exists you shadow it by using the same name.

case `x`

uses the value of the variable x which was declared before and would only match inputs with same values.

聚苯乙烯

如果变量名大写,则可以不打勾

case Pi

观看释放的模式匹配以获取更多信息。

    公众号
    关注公众号订阅更多技术干货!