sudom82 sudom82 - 6 months ago 57
Scala Question

Having trouble with Options

I feel like I'm using options incorrectly here, but can't see how to use getOrElse properly so that my condition works.

Current bad code:

if (car.getWheel.isDefined) {
else {
// Do nothing

I'd like to use something simple like getOrElse instead of this ugly combination of an if statement and using '.get'. A match expression would do the same thing as the if statement, but again take up three lines and basically be reinventing Option. Is there some method in Option that lets me do nothing to Nones?

My goal: If the option contains None, I'd like to have the line of code accomplish nothing. I don't want to call getHubCap on some parameter of getOrElse.


You could use map:

val result: Option[Boolean] =

The code inside map will execute only when the Option is Some. It's treating the Option type as a list with one or no elements. When you map on an empty list you just get an empty list back; when you map on a single-element list, you get a new single-element list but with a mapped value