Search code examples
scalascala-option

How to convert/wrap a sequence in scala to an Option[Seq] so that if the list is empty, the Option is None


I could do this with an if an statement, but there is probably a "scala" way to do this.

  def notScalaConv(in: Seq[String]): Option[Seq[String]] = {
    if (in.isEmpty)
      None
    else
      Option(in)
  }

Solution

  • You can lift your Seq to an Option, and then filter it. Like this:

     def notScalaConv(in: Seq[String]): Option[Seq[String]] = {
         Option(in).filter(_.nonEmpty)
     }