Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of using some Scala Option methods

I have read the blog post recommended me here. Now I wonder what some those methods are useful for. Can you show examples of using forall (as opposed to foreach) and toList of Option?

like image 516
Michael Avatar asked Jul 26 '11 16:07

Michael


People also ask

What is option in Scala give an example?

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.

What is some () in Scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some.

Why do we use option in Scala?

Scala's Option is particularly useful because it enables management of optional values in two self-reinforcing ways: Type safety – We can parameterize our optional values. Functionally aware – The Option type also provides us with a set of powerful functional capabilities that aid in creating fewer bugs.

How does Option work in Scala?

Scala Option is used in Scala Object-oriented programming whenever the return type of function can be a null. It has the values of a type or none in it, so the method returns an instance of option with the values whether be it any values or none.


3 Answers

  • map: Allows you to transform a value "inside" an Option, as you probably already know for Lists. This operation makes Option a functor (you can say "endofunctor" if you want to scare your colleagues)
  • flatMap: Option is actually a monad, and flatMap makes it one (together with something like a constuctor for a single value). This method can be used if you have a function which turns a value into an Option, but the value you have is already "wrapped" in an Option, so flatMap saves you the unwrapping before applying the function. E.g. if you have an Option[Map[K,V]], you can write mapOption.flatMap(_.get(key)). If you would use a simple map here, you would get an Option[Option[V]], but with flatMap you get an Option[V]. This method is cooler than you might think, as it allows to chain functions together in a very flexible way (which is one reason why Haskell loves monads).
  • flatten: If you have a value of type Option[Option[T]], flatten turns it into an Option[T]. It is the same as flatMap(identity(_)).
  • orElse: If you have several alternatives wrapped in Options, and you want the first one that holds actually a value, you can chain these alternatives with orElse: steakOption.orElse(hamburgerOption).orElse(saladOption)
  • getOrElse: Get the value out of the Option, but specify a default value if it is empty, e.g. nameOption.getOrElse("unknown").
  • foreach: Do something with the value inside, if it exists.
  • isDefined, isEmpty: Determine if this Option holds a value.
  • forall, exists: Tests if a given predicate holds for the value. forall is the same as option.map(test(_)).getOrElse(true), exists is the same, just with false as default.
  • toList: Surprise, it converts the Option to a List.
like image 86
Landei Avatar answered Oct 17 '22 01:10

Landei


Many of the methods on Option may be there more for the sake of uniformity (with collections) rather than for their usefulness, as they are all very small functions and so do not spare much effort, yet they serve a purpose, and their meanings are clear once you are familiar with the collection framework (as is often said, Option is like a list which cannot have more than one element).

forall checks a property of the value inside an option. If there is no value, the check pass. For example, if in a car rental, you are allowed one additionalDriver: Option[Person], you can do

additionalDriver.forall(_.hasDrivingLicense)

exactly the same thing that you would do if several additional drivers were allowed and you had a list.

toList may be a useful conversion. Suppose you have options: List[Option[T]], and you want to get a List[T], with the values of all of the options that are Some. you can do

for(option <- options; value in option.toList) yield value

(or better options.flatMap(_.toList))

like image 36
Didier Dupont Avatar answered Oct 17 '22 03:10

Didier Dupont


I have one practical example of toList method. You can find it in scaldi (my Scala dependency injection framework) in Module.scala at line 72:

https://github.com/OlegIlyenko/scaldi/blob/f3697ecaa5d6e96c5486db024efca2d3cdb04a65/src/main/scala/scaldi/Module.scala#L72

In this context getBindings method can return either Nil or List with only one element. I can retrieve it as Option with discoverBinding. I find it convenient to be able to convert Option to List (that either empty or has one element) with toList method.

like image 24
tenshi Avatar answered Oct 17 '22 03:10

tenshi