In this code, given a structure Seq[Seq[String]]
I'm trying to get rid of element "B" in each sequence. To do that, my intent is to replace the field with None
and then flatten the Seq. Problem is that the flatten statement does not compile, why is that and how to fix this?
object HelloScala extends App{
Seq(Seq("A","B","C"),Seq("A","B","C")).map{ rec =>
val rec2 = rec.zipWithIndex.map{ case (field, i) =>
if (field == "B")
None
else
field + i
}
println(rec2.flatten)
}
}
The result of an assignment is Unit
. Not what you want in a map()
.
The compliment of None
is Some()
, which you'll want to use to keep the result type consistent.
map()
followed by flatten
can be combined in a flatMap()
.
-
Seq(Seq("A","B","C"),Seq("A","B","C")).map { rec =>
rec.zipWithIndex.flatMap { case (field, i) =>
if (field == "B")
None
else
Some(field + i)
}
}
//res0: Seq[Seq[String]] = List(List(A0, C2), List(A0, C2))