【问题标题】:for comprehension to yield map为了理解产生地图
【发布时间】:2016-07-22 05:53:20
【问题描述】:

我尝试使用 for comprehension 将字符串映射到 MyData 案例类。

这是我尝试失败的方法:

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
}

这段代码给了我多个编译错误。构建这种用于理解和生成地图的巢的正确方法是什么?

【问题讨论】:

  • 你得到什么编译错误?

标签: scala for-comprehension


【解决方案1】:

使用for comprehensions,您的代码应如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多