2
votes

My program receives a scala map, the requirements is to validate this map (key-value pairs). Ex: validate a key value, convert its type from string to int etc. In a rare case, we update the key as well before passing the map to the down layer. Its not always required to update this map , but only when we detect that there are any unsupported keys or values. I'm doing some thing like this:

private def updateMap ( parameters: Map[String, String]): Map[String, String] = {

parameters.map{

  case(k,v) => k match { case "checkPool" =>


    (k, (if (k.contains("checkPool"))
      v match {
        case "1" => "true"
        case _ => "false"
      }
    else v))

  case "Newheader" => (k.replace("Newheader","header"),v)
  case _ =>(k,v)
  }


  case _ => ("","")
}

} Like this the code increases for doing the validation and converting the keys/values to supported ones. Is there a cleaner way of doing this validation in Scala for a map?

Regards

1
edited the question with more details - Garipaso

1 Answers

0
votes

According to what I understood from your question, match case can be your solution

inOptions.map(kv => kv.keySet.contains(STR) match {
  case true => mutable.HashMap(STR_UPDT->kv.get(STR).get)
  case _ => kv
})

Edited

Since you updated your question with more requirements, simple if else condition matching seems to be the best choice.

def updateMap(parameters: Map[String, String]): Map[String, String] = {
  parameters.map(kv => {
    var key = kv._1
    var value = kv._2
    if(key.contains("checkPool")){
      value = if(value.equals("1")) "true" else "false"
    }
    else if(key.contains("Newheader")){
      key = key.replace("Newheader", "header")
    }
    (key, value)
  })
}

You can add more else if conditions