作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个序列,即 prices: Seq[Price]
和 overrides: Seq[Override]
。我需要对它们施展魔法,但仅针对基于共享 ID 的子集。
所以我通过groupBy
将它们都分组到一个Map
中:
我通过以下方式进行分组:
val pricesById = prices.groupBy(_.someId) // Int => Seq[Cruise]
val overridesById = overrides.groupBy(_.someId) // // Int => Seq[Override]
我希望能够通过 flatMap
创建我想要的序列:
val applyOverrides = (someId: Int, prices: Seq[Price]): Seq[Price] => {
val applicableOverrides = overridesById.getOrElse(someId, Seq())
magicMethod(prices, applicableOverrides) // returns Seq[Price]
}
val myPrices: Seq[Price] = pricesById.flatMap(applyOverrides)
我希望 myPrices
只包含一个大的 Seq[Price]
。
然而,我在 flatMap 方法中发现了一个奇怪的类型不匹配与 NonInferedB 我无法解决。
最佳答案
在 Scala 中,映射是元组,而不是键值对。
flatMap
的函数因此只需要一个参数,即元组(key, value)
,而不是两个参数键,值
。
由于您可以通过 _1
访问元组的第一个元素,通过 _2
访问第二个元素,依此类推,您可以像这样生成所需的函数:
val pricesWithMagicApplied = pricesById.flatMap(tuple =>
applyOverrides(tuple._1, tuple._2)
另一种方法是用例匹配:
val pricesWithMagicApplied: Seq[CruisePrice] = pricesById.flatMap {
case (someId, prices) => applyOverrides(someId, prices)
}.toSeq
关于scala - 如何在 scala map 上使用 map/flatMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47457977/
我是一名优秀的程序员,十分优秀!