Search code examples
scalamonadsscala-option

Dealing Options from a Map.get in Scala


I've a Scala Map that contains a bunch of parameters that I get in a HTTP request.

val queryParams = Map( ("keyword" -> "k"), ("from" -> "f"), ("to" -> "t"), ("limit" -> "l") ) 

I've a method that takes all these parameters.

def someMethod( keyword: String, from: String, to: String, limit: String) = { //do something with input params }

I want to pass the parameters from the map into my method someMethod.

queryParams.get returns an 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 ?


Solution

  • If all the parameters have the same default value you can set a default value to 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 which for any non exist value return the default value. Now that you are sure you always get a value you can use queryParams("keyword") (without the get function).