Scala 模式匹配中 case 子句中的映射表达式 [英] map expression in case clause in scala pattern matching
问题描述
我有一个配置值,它与地图中的值之一匹配,并根据它匹配的值我采取行动.这是我正在尝试做的一些示例代码
I have a configuration value that matches to one of the values in a map and depending on to which it matches i take an action. Here is some sample code of what i am trying to do
val x = 1 // or 2 or 3
val config = Map("c1"-> 1, "c2"-> 2, "c3"-> 3)
x match {
case config("c1") =>
println("1")
case config("c2") =>
println("2")
case config("c3") =>
println("3")
}
现在应该打印 1
因为 config("c1")
计算结果为 1
但它给出了错误
Now this should print 1
because config("c1")
evaluates to 1
but it gives error
error: value config is not a case class, nor does it have an unapply/unapplySeq member
case config("c1") =>
其他两种情况类似.为什么我要在这里取消申请?有什么指点吗?
Similarly for the other 2 cases. Why should i have an unapply here? Any pointers?
推荐答案
这样的表达式看起来像一个 extractor,因此是关于 unapply/unapplySeq
方法的消息.如果您不想使用提取器而只想匹配一个普通值,您需要将该值存储在一个稳定的标识符中——您不能使用任意表达式作为匹配案例:
An expression like that looks like an extractor, hence the message about unapply/unapplySeq
methods. If you don't want to use an extractor but just want to match against a plain value, you need to store that value in a stable identifier - you can't use an arbitrary expression as a match case:
val case1 = config("c1")
x match {
case case1 => println("1")
...
}
这篇关于Scala 模式匹配中 case 子句中的映射表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!