Why using foreach
, map
, flatMap
etc. are considered better than using get
for Scala Options? If I useisEmpty
I c
The reason it's more useful to apply things like map
, foreach
, and flatMap
directly to the Option
instead of using get
and then performing the function is that it works on either Some
or None
and you don't have to do special checks to make sure the value is there.
val x: Option[Int] = foo()
val y = x.map(_+1) // works fine for None
val z = x.get + 1 // doesn't work if x is None
The result for y
here is an Option[Int]
, which is desirable since if x
is optional, then y
might be undetermined as well. Since get
doesn't work on None
, you'd have to do a bunch of extra work to make sure you didn't get any errors; extra work that is done for you by map
.