Mapget processing options in Scala
I have Scala Map
that contains a bunch of parameters that I receive in an HTTP request.
val queryParams = Map( ("keyword" -> "k"), ("from" -> "f"), ("to" -> "t"), ("limit" -> "l") )
I have a method that takes all of these parameters.
def someMethod( keyword: String, from: String, to: String, limit: String) = { //do something with input params }
I want to pass parameters from the map to my method someMethod
.
queryParams.get
returns Option
. So I can call something like queryParams.get("keyword").getOrElse("")
for each input parameter.
someMethod( queryParams.get("keyword").getOrElse(""), queryParams.get("from").getOrElse(""), queryParams.get("to").getOrElse(""), queryParams.get("limit").getOrElse(""))
Is there a better way?
source to share
If all parameters have the same default, you can set a default for the entire map:
val queryParams = Map( ("keyword" -> "k"), ("from" -> "f"), ("to" -> "t"), ("limit" -> "l") ).withDefaultValue("")
someMethod( queryParams("keyword"), queryParams("from"), queryParams("to"), queryParams("limit"))
withDefaultValue
return a map that returns the default for any non-existent value. Now that you are sure that you are always getting the value, you can use queryParams("keyword")
(without the get function).
source to share