scala list of options to option of list

To convert a Scala list of options to an option of a list, you can use the sequence method provided by the Option companion object. Here is an example:

val list: List[Option[Int]] = List(Some(1), Some(2), Some(3))

val optionList: Option[List[Int]] = Option.sequence(list)

In the above code, we have a list list of Option[Int] elements. We call the sequence method on the Option companion object and pass in the list as an argument. This method converts the list of options into an option of a list. The resulting optionList will be Some(List(1, 2, 3)) in this case.

If any of the elements in the original list are None, the resulting option will also be None. For example:

val listWithNone: List[Option[Int]] = List(Some(1), None, Some(3))

val optionListWithNone: Option[List[Int]] = Option.sequence(listWithNone)

In this case, the resulting optionListWithNone will be None because one of the elements in the original list is None.

This approach allows you to convert a list of options into an option of a list in Scala.