Scala code parser specifies variable argument names that are identical to external mapped variables - "suspicious shading"

In the following code snippet, where the outer matches vars (x, y) match the case (xx, yy):

scala> val (x,y) = (1,2)
x: Int = 1
y: Int = 2

scala> (x,y) match {
     |    case (xx:Int, yy:Int) =>  println(s"x=$x xx=$xx")
     | }
x=1 xx=1

      

We could also write this code like this:

scala> (x,y) match {
     |    case (x:Int, y:Int) =>  println(s"x=$x y=$y")
     | }
x=1 y=2

      

In this latter case, Scala code analyzers tell us:

Suspicious shading with a variable template

OK. But is there some situation where we could actually use an internal variable (x or y) instead of the original external match variables?

It seems that this is purely stylistics? No real room for error? If so, I would be interested to know what errors there might be.

+3


source to share


2 answers


This can be confusing:

val x = Some(1)
val y = Some(2)

(x, y) match {
    case (Some(x), Some(y)) => println(s"x=$x y=$y")
}

      

x

and y

have different types depending on whether you are inside or outside match

. If this code was not easy to use Option

and was several lines longer, it can be quite difficult to explain.



Can errors arise from this? Nothing I can think of is terribly far-fetched. You might, for example, go wrong one by one.

val list = List(1,2,3)
list match {
    case x :: y :: list => list // List(3) and not List(1,2,3)
    case x :: list => list      // List with 1 element, should the outer list have size 2
    case _ => list              // Returns the outer list when empty
}

      

Not to mention what a terrible mess. Internally match

, list

sometimes refers to an internal symbol and sometimes an external one list

.

+2


source


It is just code that is unnecessarily difficult to read and understand, there are no special errors that can occur.



0


source







All Articles