在scala模式匹配中,可变模式的可疑阴影是什么? [英] In scala pattern matching, what is suspicious shadowing by a variable pattern?

查看:422
本文介绍了在scala模式匹配中,可变模式的可疑阴影是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Intellij中键入以下代码时,会突出显示匹配中的x,并显示警告可变模式的可疑阴影

When I type the following code into Intellij, it highlights the x inside the match with the warning "Suspicious shadowing by a Variable Pattern"

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

这表明我将其更改为:

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

什么是可疑阴影以及反对做什么?!

What is suspicious shadowing and what do the backticks do?!

推荐答案

case x

创建一个名为 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`

使用之前声明的变量 x 的值,并且只匹配具有相同值的输入。

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

PS

如果变量的名称大写为

case Pi

这篇关于在scala模式匹配中,可变模式的可疑阴影是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆