Search code examples
scalafor-comprehension

for comprehension to yield map


I try to use for comprehension to make a map of string to MyData case class.

Here is what I tried unsuccessfully :

case class MyDataProperty(name: String, value: String)
case class MyData(props: List[MyDataProperty])


def makeMyData(configs: List[Config]): Map[String, MyData] = {
    for {
      // loop through all configurations
      conf <- configs
      // Retrieve each config's list of properties and make a list of MyDataProperty object from it
      props <- for(prop <- conf.properties) yield (MyDataProperty(prop.name, prop.value))
    } yield (conf.name -> MyData(props)) toMap
}

This code gives me multiple compile errors. What is the correct way to build this kind of nest for comprehension and yield a map ?


Solution

  • With for comprehensions your code should look like following:

    def makeMyData(configs: List[Config]): Map[String, MyData] =
      (for {
        conf <- configs
        props = for (prop <- conf.properties) yield MyDataProperty(prop.name, prop.value)
      } yield conf.name -> MyData(props)).toMap