使用Map迭代进行理解的Scala

时间:2018-01-23 02:28:17

标签: scala yield flatmap for-comprehension

我经历了一堆代码和教程,但我仍然不明白如何通过for comprehension迭代Map。

例如:我有一张地图。键作为字符串(学生姓名),作为学生详细信息的值。我想迭代学生地图作为每个键和值。如何通过理解来实现这一目标。

这是我尝试的代码,但我不理解

for {   
  studentMap <- studRepo.getAllStudent()// returns a map
  result1 <- performSomeOper(studentMap.key) // I’m not getting an option to access the key/value
  result2 <- performSomeOper(studentMap.value)
} yield performYieldOps(result1, result2)

我在这里做错了什么?我是否需要将studentMap保持在理解之外?请把你的意见告诉我。

1 个答案:

答案 0 :(得分:1)

  for {
    (key, value) <- studRepo.getAllStudent()
    res1 <- performSomeOper(key)
    res2 <- performSomeOper(value)
  } yield ...

您可以从Map映射键,值

for comprehension实际等于flatMap,因此对于上述内容等于:

  m.flatMap {
    case (key, value) => ...
  }