Cor*_*ped 2 scala sequence option
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
})
Run Code Online (Sandbox Code Playgroud)
where res is a list containing optional list elements such as :
List(Some(Seq(foo)), Some(Seq(bar)), None, Some(Seq(baz, blah)))
Run Code Online (Sandbox Code Playgroud)
I get a compilation error at the sign ++: saying:
type mismatch; found : Iterable[Equals] required: Seq[Option[Seq[String]]]
Run Code Online (Sandbox Code Playgroud)
What am I doing wrong here?
你为什么不这样做:
res.flatten.flatten
Run Code Online (Sandbox Code Playgroud)
第一个flatten将摆脱Nones 并暴露Options,第二个将在Seqs上执行预期的展平操作