How to convert an Option[String]
to a List[String]
?
My Option[String]
looks like this : Some("value1,value2")
i tried this but with no success
def convertOptionToList(a: Option[String]): List[String] = {
return a.map(x => x.split(",").toList)
}
At the end i want something like this : List("val1","val2","val3");
Remove .toList
where you have it, and add .toList.flatten
at the end:
a.map(_.split(",")).toList.flatten
Alternatively, do .toList
first, and then .flatMap
instead of .map
:
a.toList.flatMap(_.split(","))
But, if it really looks like Some("value1","value2")
, then it is not an Option[String]
to begin with. It is an Option[(String, String)]
. A tuple inside the Option
is a pair of strings. Do this in this case:
a.toList.flatMap { case (a,b) => Seq(a,b) }
(although, I don't think it makes much sense to be converting tuples to lists. tuples are better).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With