Is it possible to get all entries of a List[Option[T]]
having a value?
Example:
val list = List(None, Some(1), None, Some(2))
list.filter(_.isDefined).map(_.get)
result:
List[Int] = List(1, 2)
Is there a method to do it in one step? It's a common case, isn't it?
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
Lists. Lists preserve order, can contain duplicates, and are immutable.
Note that
list.flatten
Will do just as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With