Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all entries having a value from List[Option] in Scala

Tags:

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?

like image 354
deamon Avatar asked Jan 17 '13 08:01

deamon


People also ask

What is option () in Scala?

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.

What does :+ mean in Scala?

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.

How do you use some and options in Scala?

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.

Does Scala list preserve order?

Lists. Lists preserve order, can contain duplicates, and are immutable.


1 Answers

Note that

 list.flatten

Will do just as well.

like image 153
Faiz Avatar answered Oct 02 '22 17:10

Faiz