我尝试用于理解,将字符串映射到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
}
这段代码给了我多个编译错误。构建这种嵌套以获得理解并生成地图的正确方法是什么?
答案 0 :(得分:0)
使用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