sudom82
sudom82

Reputation: 135

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) {
    car.getWheel.get.getHubCap.isShinierThan(hubcap2)
}
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.

Upvotes: 0

Views: 63

Answers (2)

toidiu
toidiu

Reputation: 965

I tend to use map to separate out my cases. The case _ could important because it is the default case and will match if none of the prior cases matched. This lets you code in a predictive manner and handle all edge cases.

As you can see it is also possible to add conditions by using if clause within the case statements.

val opt: Option[String] = Some("foo")

val printString: String = opt match {
  case Some(string) if string == "bar" => string
  case Some(string) => string
  case _ => "none"
} 

println(printString)

Upvotes: 0

Ori Popowski
Ori Popowski

Reputation: 10662

You could use map:

val result: Option[Boolean] = car.getWheel.map(_.getHubCap.isShinierThan(hubcap2))

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

Upvotes: 4

Related Questions