Khan Saab
Khan Saab

Reputation: 511

Replacing a value in nested map

I have nested map and i want to replace the values in that map for a specific key. I also want to preserve the nested structure of the map. Here is my attempt to replace the values but it is not working.

 def replaceValuesInMap(input:Map[String,Any],inputkey:String,inputValue:String): Map[String, Any] = {
    val output = input.map(x => x match {
      case ((key, value:String)) => {
        if (key == inputkey)
          (key -> inputValue)
        else
          (key -> value)
      }
      case ((_, value: Map[String, Any])) => replaceValuesInMap(value, inputkey, inputValue)
    })
    output.toMap
  }

I get the following error:

Type mismatch:
Required: Map[String,Any]
Found: Map[Nothing,Nothing]

What is wrong with this code?

Upvotes: 0

Views: 196

Answers (1)

esse
esse

Reputation: 1551

You should change this line

case ((_, value: Map[String, Any])) => replaceValuesInMap(value, inputkey, inputValue)

to

case ((key, value: Map[String @unchecked, _ ])) => key -> replaceValuesInMap(value, inputkey, inputValue)

Upvotes: 3

Related Questions