理解 yield map
for comprehension to yield map
我尝试使用 for comprehension 将字符串映射到 MyData 大小写 class。
以下是我尝试失败的方法:
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
}
这段代码给我多个编译错误。这种理解窝和出图的正确搭建方法是什么?
使用 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
我尝试使用 for comprehension 将字符串映射到 MyData 大小写 class。
以下是我尝试失败的方法:
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
}
这段代码给我多个编译错误。这种理解窝和出图的正确搭建方法是什么?
使用 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