Torque
Torque

Reputation: 117

Unable to return Map from a scala method

I am trying to return a Map from a scala method as below.

I have two different Maps with some matching keys. I need to find the matching keys between them and pick the values out of them and put them in another Map in the way I wanted. Below is the code I wrote for the aforementioned action.

val common      = rdKeys.keySet.intersect(bounds.keySet).toList
val metaColumns = getReadColumns(common, rdKeys, bounds)
def getReadColumns(common:List[String], rdKeys:scala.collection.mutable.Map[String, String], bounds:scala.collection.mutable.Map[String, String]): scala.collection.mutable.Map[String, String] = {
  var metaMap = scala.collection.mutable.Map[String, String]
  common.map {
    c => metaMap += (c -> bounds(c) + "|" + rdKeys(c))
  }
  metaMap
}

But the method is giving me a compilations error:

Expression of type Seq[(String, String)] => mutable.Map[String, String] doesn't confirm to expected type mutable.Map[String, String]

All the method parameters, Maps used inside the method & the return type of the method are of mutable.Map[String, String]. I don't understand what is the mistake I did here. Could anyone let me know what do I have to do to correct the problem ?

Upvotes: 2

Views: 1200

Answers (2)

Matthew I.
Matthew I.

Reputation: 1813

You got the error

Expression of type Seq[(String, String)] => mutable.Map[String, String] doesn't confirm to expected type mutable.Map[String, String]

Because of the statement scala.collection.mutable.Map[String, String] returns a function Seq[(String, String)] => mutable.Map[String, String]

You can correct it by empty method:

      def getReadColumns( common:List[String], 
                        rdKeys:scala.collection.mutable.Map[String, String], 
                        bounds:scala.collection.mutable.Map[String, String]):scala.collection.mutable.Map[String, String] = {

      val metaMap = scala.collection.mutable.Map.empty[String, String]
      common.foreach {
        c => metaMap.update(c, bounds(c) + "|" + rdKeys(c)) 
      }
      metaMap
    }

P.S. or use c => metaMap += c -> (bounds(c) + "|" + rdKeys(c))

Upvotes: 4

w4bo
w4bo

Reputation: 905

map preserves the collection type. You can map a List to another List, and, in the end, cast your List directly to a Map

val common = List("a", "b")
val rdKeys = Map("a" -> 1, "b" -> 1)
val bounds = Map("a" -> 10, "b" -> 10)
common // this is a list
     .map(c => c -> (bounds(c) + "|" + rdKeys(c))) // this is a list
     .toMap // then cast to it to a Map

This code outputs

scala.collection.immutable.Map[String,String] = Map(a -> 10|1, b -> 10|1)

Upvotes: 3

Related Questions