范围内变量的模式匹配(Scala) [英] Pattern match for variable in scope (Scala)
本文介绍了范围内变量的模式匹配(Scala)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码中
val x = 5
val y = 4 match {
case x => true
case _ => false
}
值y
为true. Scala将x
解释为模式匹配中的自由变量,而不是将其绑定到范围中具有相同名称的变量.
the value y
is true. Scala interprets x
to be a free variable in the pattern match instead of binding it to the variable with the same name in the scope.
如何解决这个问题?
推荐答案
援引最小惊讶原则,我将简单地这样做:
Invoking the least astonishment principle, I will simply do:
val x = 5
val y = 4 match {
case z if z == x => true
case _ => false
}
这篇关于范围内变量的模式匹配(Scala)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文