3

I have two sequences, i.e. prices: Seq[Price] and overrides: Seq[Override]. I need to do some magic on them yet only for a subset based on a shared id.

So I grouped them both into a Map each via groupBy:

I do the group by via:

val pricesById = prices.groupBy(_.someId) // Int => Seq[Cruise]
val overridesById = overrides.groupBy(_.someId) // // Int => Seq[Override]

I expected to be able to create my wanted sequence via 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)

I expected myPrices to contain just one big Seq[Price].

Yet I get a weird type mismatch within the flatMap method with NonInferedB I am unable to resolve.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347

1 Answers1

1

In scala, maps are tuples, not a key-value pair.

The function for flatMap hence expects only one parameter, namely the tuple (key, value), and not two parameters key, value.

Since you can access first element of a tuple via _1, the second via _2 and so on, you can generate your desired function like so:

val pricesWithMagicApplied = pricesById.flatMap(tuple => 
  applyOverrides(tuple._1, tuple._2)

Another approach is to use case matching:

val pricesWithMagicApplied: Seq[CruisePrice] = pricesById.flatMap {
  case (someId, prices) => applyOverrides(someId, prices)
}.toSeq
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • 2
    In Scala map is a collection of `Key and value` pairs. check the https://docs.scala-lang.org/overviews/collections/maps.html – Indrajit Swain Nov 23 '17 at 16:58