Search code examples
scalafunctional-programming

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


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?


Solution

  • 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
    ...