Johnny
Johnny

Reputation: 15413

Scala idiomatic way of treating Option[DataType[Option[Boolean]]]

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

Answers (1)

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

Related Questions