Convert a List into an Option if it is populated

Lee's answer is good, but I think this corresponds to the intention a bit more clearly:

Option(myList).filter(_.nonEmpty).map(Bar)

Starting Scala 2.13, Option has a when builder:

Option.when(condition)(result)

which in our case gives:

Option.when(myList.nonEmpty)(Bar(myList))
// val myList = List[Int]()    =>    Option[Bar] = None
// val myList = List(1, 2)     =>    Option[Bar] = Some(Bar(List(1, 2)))

Also note Option.unless which promotes the opposite condition:

Option.unless(myList.isEmpty)(Bar(myList))
// val myList = List[Int]()    =>    Option[Bar] = None
// val myList = List(1, 2)     =>    Option[Bar] = Some(Bar(List(1, 2)))

Tags:

Scala