Reputation: 15413
What is the Scala idiomatic what of handling an expression of type Option[Data[Option[Boolean]]]
when we need to know if the internal Boolean
is true?
That's what I did:
val isProperty: Boolean = maybeData.exists(_.isProperty.exists(a => a))
But I feel it's not optimal. Any alternatives?
Upvotes: 1
Views: 81
Reputation: 22850
IMHO, the best way to handle nested options is to "flatten" them into a single one using flatMap
val maybeProperty = maybeData.flatMap(_.isProperty)
Now, there are multiple ways to turn that Option[Boolean]
into a Boolean
maybeProperty.contains(true)
maybeProperty.getOrElse(false)
maybeProperty.fold(ifEmpty = false)(identity)
maybeProperty.exists(identity)
maybeProperty.filter(identity).nonEmpty
And probably may more but they start to become more and more obscure.
I would recommend the first two; whichever you find more readable.
Upvotes: 2