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

Viewed 82

I am having Option of List of String like, Some(List("abc","def","ghi")) and I need to convert to List("abc","def","ghi") in Scala. I Mean Option[List[String]] to List[String].

2 Answers

You should check the documentation for Option. You will find everything you'll need there.

Here are 2 ideas:

  val optlist = Some(List("abc", "def", "ghi"))
  val list = if (optlist.isDefined) optlist.get else Nil
  val list2 = optlist.getOrElse(Nil)
  println(list)
  println(list2)

Output:

List(abc, def, ghi)
List(abc, def, ghi)

If you want to remove Option in Scala then you can use getOrElse() function.

Scala is a very strong typesafe language which detects compilation errors. In the else part you should return the same type of data, for example:

val nameOption : Option[String] = Some("ABC");

then to remove Option you should use getOrElse()

val name: String = nameOption.getOrElse(" ") #Empty String

Similarly, In your case,

val listOption = Some(List("abc", "def", "ghi"))

val list : List[String] = listOption.getOrElse(List.empty)

Output :

List(abc, def, ghi)
Related