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(_)
}
It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala's root class to make its availability to the all objects.
Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }
The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches.
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)
}
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With