Scala 大小写匹配默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20148556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:53:14  来源:igfitidea点击:

Scala case match default value

scala

提问by Caballero

How can I get the default value in match case?

如何在匹配案例中获得默认值?

//Just an example, this value is usually not known
val something: String = "value"

something match {
    case "val" => "default"
    case _ => smth(_) //need to reference the value here - doesn't work
}

UPDATE:I see that my issue was not really understood, which is why I'm showing an example which is closer to the real thing I'm working on:

更新:我发现我的问题没有被真正理解,这就是为什么我要展示一个更接近我正在研究的真实事物的例子:

val db =    current.configuration.getList("instance").get.unwrapped()
            .map(f => f.asInstanceOf[java.util.HashMap[String, String]].toMap)
            .find(el => el("url").contains(referer))
            .getOrElse(Map("config" -> ""))
            .get("config").get match {
                case "" => current.configuration.getString("database").getOrElse("defaultDatabase")
                case _  => doSomethingWithDefault(_)
            }

回答by om-nom-nom

something match {
    case "val" => "default"
    case default => smth(default)
}

It is not a keyword, just an alias, so this will work as well:

它不是关键字,只是别名,所以这也可以:

something match {
    case "val" => "default"
    case everythingElse => smth(everythingElse)
}

回答by Joyfulvillage

The "_" in Scala is a love-and-hate syntax which could really useful and yet confusing.

Scala 中的“_”是一种又爱又恨的语法,它可能非常有用但又令人困惑。

In your example:

在你的例子中:

something match {
    case "val" => "default"
    case _ => smth(_) //need to reference the value here - doesn't work
}

the _ means, I don't care about the value, as well as the type, which means you can't reference to the identifier anymore. Therefore, smth(_) would not have a proper reference.
The solution is that you can give the a name to the identifier like:

_ 表示,我不关心值以及类型,这意味着您不能再引用标识符。因此, smth(_) 不会有正确的引用。
解决方案是您可以为标识符指定一个名称,例如:

something match {
    case "val" => "default"
    case x => smth(x)
}

I believe this is a working syntax and x will match any value but not "val".

我相信这是一种有效的语法,x 将匹配任何值,但不匹配“val”。

More speaking. I think you are confused with the usage of underscore in map, flatmap, for example.

说多了。例如,我认为您对 map、flatmap 中下划线的使用感到困惑。

val mylist = List(1, 2, 3)
mylist map { println(_) }

Where the underscore here is referencing to the iterable item in the collection. Of course, this underscore could even be taken as:

这里的下划线是指集合中的可迭代项。当然,这个下划线甚至可以理解为:

mylist map { println } 

回答by Dan

here's another option:

这是另一种选择:

something match {
    case "val" => "default"
    case default@_ => smth(default)
}