J Costa
J Costa

Reputation: 23

Scala: Use map function tuples in a subsequent flatMap

I want to use a tuple of a map function in a subsequent flatMap.

Like this:

val list = orders.map(ord => (ord.prod.tasks, ord.quantity))
                 .zipWithIndex flatMap {
                   case (variable, index) =>
                     createSchedules(variable._1.size * variable._2, ord, null)
                 }

Is there a way in which I can use it or do you think that I have to change the way that I'm thinking about the solution?

Upvotes: 0

Views: 423

Answers (2)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

First of all, judging from the parameters that you're passing to createSchedules, it looks as if that function can be simplified to (I'm ignoring the null parameter for now):

def createSchedules(order: Order): List[Schedule] = {
  val num = order.prod.tasks.size * order.quantity
  // do stuff
}

Also, the initial map is unnecessary. list can be simplified to:

val list = orders.zipWithIndex
                 .flatMap {
                   case (order, index) =>
                     createSchedules(order)
                 }

It's unclear what you need the index for, though.

Upvotes: 1

FabFlying
FabFlying

Reputation: 163

I want to use a tuple of a map function in a subsequent flatMap.

Here's a working example of using tuples in a subsequent flatMap

val input = List("a", "b", "c")
val list = input.map(i => (i + "A", i + "B")).zipWithIndex flatMap{ case (variable, index)=> variable._1 + variable._2}

Issue with original code

val list = orders.map(ord => (ord.prod.tasks, ord.quantity)).zipWithIndex flatMap{case (variable, index)=>createSchedules(variable._1.size * variable._2, ord, null)}

One issue is that ord is out of scope in the 'createSchedules' call.

ord will only be visible in the initial 'orders.map' scope.

Upvotes: 1

Related Questions