Scala case match default value

2020-05-16 23:50发布

问题:

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(_)
            }

回答1:

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)
}


回答2:

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

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:

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".

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

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 } 


回答3:

here's another option:

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


标签: scala