Home > Software engineering >  Scala idiomatic way of treating Option[DataType[Option[Boolean]]]
Scala idiomatic way of treating Option[DataType[Option[Boolean]]]

Time:02-02

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?

CodePudding user response:

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.

  •  Tags:  
  • Related