Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

intellij idea - In scala pattern matching, what is suspicious shadowing by a variable pattern?

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 =>
}

It suggests that I change it to:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

PS

You can leave the back ticks out if the name of the variable is capitalized as in

case Pi

Watch Pattern Matching Unleashed for more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...