You can do it beautifully using a semigroup adding with a fairy tale or cats:
import scalaz._, Scalaz._ // for cats use `import cats._, implicits._` val opt1 = Option(List("Sal", "Salil")) val opt2 = Option(List("Sal2", "Salil2")) scala> opt1 |+| opt2 res0: Option[List[String]] = Some(List(Sal, Salil, Sal2, Salil2)) scala> opt1 |+| None res1: Option[List[String]] = Some(List(Sal, Salil)) scala> Option.empty[List[String]] |+| None res2: Option[List[String]] = None
Otherwise, with the standard library, you may need to process it in each case:
(opt1, opt2) match { case (Some(a), Some(b)) => Option(a ++ b) case (Some(a), None) => Option(a) case (None, Some(b)) => Option(b) case _ => None }
Or use collection methods to smooth them:
scala> List(opt1, opt2).flatten.flatten res5: List[String] = List(Sal, Salil, Sal2, Salil2) scala> List(opt1, None).flatten.flatten res6: List[String] = List(Sal, Salil)
source share