Home > Net >  Scala map with function call results in references to the function instead of results
Scala map with function call results in references to the function instead of results

Time:01-07

I have a list of keys for which I want to fetch data. The data is fetched via a function call for each key. I want to end up with a Map of key -> data. Here's what I've tried:

  case class MyDataClass(val1: Int, val2: Boolean)

  def getData(key: String): MyDataClass = {
    // Dummy implementation
    MyDataClass(1, true)
  }

  def getDataMapForKeys(keys: Seq[String]): Map[String, MyDataClass] = {
    val dataMap: Map[String, MyDataClass] =  keys.map((_, getData(_))).toMap
    dataMap
  }

This results in a type mismatch error:

type mismatch;
 found   : scala.collection.immutable.Map[String,String => MyDataClass]
 required: Map[String,MyDataClass]
    val dataMap: Map[String, MyDataClass] =  keys.map((_, getData(_))).toMap

Why is it setting the values in the resulting Map to instances of the getData() function, rather than its result? How do I make it actually CALL the getData() function for each key and put the results as the values in the Map?

CodePudding user response:

The code you wrote is the same as the following statements:

keys.map((_, getData(_)))

keys.map(x => (x, getData(_)))

keys.map(x => (x, y => getData(y)))

This should clarify why you obtain the error.

As suggested in the comments, stay away from _ unless in simple cases with only one occurrences.

CodePudding user response:

The gist of the issue is (_, getData(_))) is creating a Tuple instead of a map entry for each key that is being mapped over. Using -> creates a Map which is what you want.

...
val dataMap: Map[String, MyDataClass] =  keys.map(key =>  (key -> getData(key))).toMap
...
  • Related