Search code examples
scalaplayframeworksbtimplicit

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


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


Solution

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