joesan
joesan

Reputation: 15385

Functional style in Scala to collect results from a method

I have two lists that I zip and go through the zipped result and call a function. This function returns a List of Strings as response. I now want to collect all the responses that I get and I do not want to have some sort of buffer that would collect the responses for each iteration.

seq1.zip(seq2).foreach((x: (Obj1, Obj1)) => {
  callMethod(x._1, x._2) // This method returns a Seq of String when called
}

What I want to avoid is to create a ListBuffer and keep collecting it. Any clues to do it functionally?

Upvotes: 1

Views: 608

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272297

Why not use map() to transform each input into a corresponding output ? Here's map() operating in a simple scenario:

scala> val l = List(1,2,3,4,5)
scala> l.map( x => x*2 )
res60: List[Int] = List(2, 4, 6, 8, 10)

so in your case it would look something like:

seq1.zip(seq2).map((x: (Obj1, Obj1)) => callMethod(x._1, x._2))

Given that your function returns a Seq of Strings, you could use flatMap() to flatten the results into one sequence.

Upvotes: 3

Related Questions