gpt4 book ai didi

scala - 如何在 scala map 上使用 map/flatMap?

转载 作者:行者123 更新时间:2023-12-05 06:37:35 25 4
gpt4 key购买 nike

我有两个序列,即 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com