Question

I need to make a sequence that, given a list containing optional list of strings, concatenates all of them to make a new list. This how my code looks like:

      res.foldLeft(Seq[Option[Seq[String]]]())((acc, v) => v match {
      case Some(x) => acc ++: Some(x)
      case None => acc
    })

where res is a list containing optional list elements such as :

List(Some(Seq(foo)), Some(Seq(bar)), None, Some(Seq(baz, blah)))

I get a compilation error at the sign ++: saying:

  type mismatch; found : Iterable[Equals] required: Seq[Option[Seq[String]]]

What am I doing wrong here?

Was it helpful?

Solution

Why don't you just do:

res.flatten.flatten

first flatten will get rid of Nones and expose the Options and second one will perform the expected flattening operation on the Seqs

OTHER TIPS

I don't have scala installed on this box, but you could try using the 'map' function to remove the options out of the equation, then flatten the list of seq down to a single iterable.

Something like this:

res.map.flatten

As I understand it you would then end up with a Iterable containing 'foo', 'bar', 'sez', 'bar'.

I'll check this out a little later to test the syntax is correct and what I've written actually works..

Cheers, Aaron

EDIT: Got access to my scala terminal and this works:

res.map(s => s).flatten.flatten

Your types in case Some(x) => acc ++: Some(x) part is wrong.

++: operator expects a parameter of type Seq[Option[Seq[String]]] but you are providing a parameter of type Option[Seq[String]].

ps: If you can tell exactly the result you expect. I can improve this answer to help you to write the correct code you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top