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
?
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.
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.
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.
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.
map
: Allows you to transform a value "inside" an Option
, as you probably already know for List
s. 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 Option
s, 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
. 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)
)
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.
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