2

I have

val str = "abc:def"
val pattern = "(.*):.*".r
val prefix = str match {
  case pattern(prefix) => prefix
  case _ => ""
}

I want to avoid MatchError so if it matches I will return the match otherwise I will return "". This compiles and do extract "prefix = "abc". However I get a warning saying

Suspicious shadowing by a Variable Pattern

IDE is suggesting putting `` around pattern(`prefix`).

Is there a better way of doing this? Why is the IDE suggesting that solution.

3 Answers 3

3

The IDE shows the warning because you have 2 variables with the same name, I would suggest renaming the inner variable to something different:

val prefix = str match {
  case pattern(pref) => pref
  case _ => ""
}

The back ticks suggestion is not what you want in this case, you would use that if you wanted to match against the value of a variable (the IDE thinks you want that because prefix is the name of an existing variable).

Sign up to request clarification or add additional context in comments.

Comments

3

You can rewrite it like below, using any other name for the prefix extracted from the pattern, because that value is then returned by the match and assigned to prefix

val str = "abc:def"
val pattern = "(.*):.*".r
val prefix = str match {
  case pattern(aaa) => aaa
  case _ => ""
}

Comments

2

Alternatively,

scala> val prefix = pattern.unapplySeq(str).map(_.head).getOrElse("")
prefix: String = abc

scala> val prefix = pattern.findPrefixMatchOf(str).map(_.group(1)).getOrElse("")
prefix: String = abc

Avoids inventing names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.