In case of important parameters of the scala function?

relative to the following scala code, the m2a and m2b functions apparently differ only in the case of the parameter, i.e. abc vs Abc. This, apparently, affects the result in accordance with the example below. When you run it with the compiler of the last 2.8, it leads to the following (I would expect that everything is correct). Any ideas would be appreciated.

m1=true m2a=true m2b=false m3=true 

the code

 package sample import scala.xml._ object ParamTest extends Application { def m1(n:Node, abc:String):Boolean = { n == <id>{Text(abc)}</id> } def m2a(n:Node, Abc:String):Boolean = n match { case <id>{Text(Abc)}</id> => true case _ => false; } // why does this one not work? def m2b(n:Node, abc:String):Boolean = n match { case <id>{Text(abc)}</id> => true case _ => false; } def m3(n:Node, abc:String):Boolean = n match { case Elem(_,"id",_,_, c @_ *) => { c contains Text(abc) } } def runner(n:Node, f:(Node, String)=>Boolean):Boolean = { f(n, "x") && !f(n, "y") && !f(n, ""); } val x = <id>x</id> println("m1="+runner(x, m1)); println("m2a="+runner(x, m2a)); println("m2b="+runner(x, m2b)); println("m3="+runner(x, m3)); } 
+4
source share
2 answers

The trick here is how Scala handles variables in case expressions. String variables in expression expressions are accepted by the compiler to introduce new variables, which are then mapped to patterns. Thus, in the m2b method, the parameter of the "abc" method is not actually used. The expression variable "abc" will match any string because it is not limited. Thus, "y" is successfully matched in the first case m2b. The top variables in the case expressions do not introduce new variables, so in m2a the match behaves as you expected.

The easiest way to match the value of a lowercase variable is to wrap it in backquotes. Thus,

 def m2b(n:Node, abc:String):Boolean = n match { case <id>{Text(`abc`)}</id> => true case _ => false; } 

will provide you with the expected results.

+5
source

When matching with a pattern, identifiers in a pattern starting with a lowercase letter are considered free pattern variables that can be bound to the values ​​in the target match value. Those that start with capital letters are the so-called stable identifiers and should already be connected in the context of the match expression, and the value of this binding should be equal to the subexpression of the target at a point in this value corresponding to this stable placement of the identifier inside the template expression.

In addition, the template variables (lower case names) corresponding to this particular example will shadow any existing binding of the same name that acts in the context of the match expression (including the expression that provides the target match value).

+5
source

Source: https://habr.com/ru/post/1313721/


All Articles