Scala 惯用的处理方式 Option[DataType[Option[Boolean]]]
Scala idiomatic way of treating Option[DataType[Option[Boolean]]]
当我们需要知道内部 Boolean
是否为真时,Scala 的惯用语是什么处理类型 Option[Data[Option[Boolean]]]
的表达式?
我就是这么做的:
val isProperty: Boolean = maybeData.exists(_.isProperty.exists(a => a))
但我觉得这不是最优的。还有其他选择吗?
恕我直言,处理嵌套选项的最佳方式是使用 flatMap
将它们 “展平” 为单个选项
val maybeProperty = maybeData.flatMap(_.isProperty)
现在,有多种方法可以将 Option[Boolean]
变成 Boolean
maybeProperty.contains(true)
maybeProperty.getOrElse(false)
maybeProperty.fold(ifEmpty = false)(identity)
maybeProperty.exists(identity)
maybeProperty.filter(identity).nonEmpty
可能还会更多,但它们开始变得越来越模糊。
我会推荐前两个;以您认为更易读的为准。
当我们需要知道内部 Boolean
是否为真时,Scala 的惯用语是什么处理类型 Option[Data[Option[Boolean]]]
的表达式?
我就是这么做的:
val isProperty: Boolean = maybeData.exists(_.isProperty.exists(a => a))
但我觉得这不是最优的。还有其他选择吗?
恕我直言,处理嵌套选项的最佳方式是使用 flatMap
val maybeProperty = maybeData.flatMap(_.isProperty)
现在,有多种方法可以将 Option[Boolean]
变成 Boolean
maybeProperty.contains(true)
maybeProperty.getOrElse(false)
maybeProperty.fold(ifEmpty = false)(identity)
maybeProperty.exists(identity)
maybeProperty.filter(identity).nonEmpty
可能还会更多,但它们开始变得越来越模糊。
我会推荐前两个;以您认为更易读的为准。