Reputation: 41
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]
.
Upvotes: 2
Views: 289
Reputation: 1
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)
Upvotes: 0
Reputation: 2638
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)
Upvotes: 5