Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Option[String]to List [String]in Scala

Tags:

scala

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");

like image 302
user708683 Avatar asked Apr 01 '16 19:04

user708683


Video Answer


1 Answers

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).

like image 143
Dima Avatar answered Sep 20 '22 12:09

Dima