Option
monad 是在 Scala 中处理“有或无”事物的一种很好的表达方式。但是,如果在“什么都没有”发生时需要记录一条消息怎么办?根据 Scala API 文档,
Either 类型通常用作 scala.Option 的替代方案,其中 Left 表示失败(按照惯例),Right 类似于 Some。
但是,我没有运气找到使用 Either 的最佳实践或涉及 Either 处理故障的良好现实世界示例。最后,我为自己的项目提出了以下代码:
def logs: Array[String] = {
def props: Option[Map[String, Any]] = configAdmin.map{ ca =>
val config = ca.getConfiguration(PID, null)
config.properties getOrElse immutable.Map.empty
}
def checkType(any: Any): Option[Array[String]] = any match {
case a: Array[String] => Some(a)
case _ => None
}
def lookup: Either[(Symbol, String), Array[String]] =
for {val properties <- props.toRight('warning -> "ConfigurationAdmin service not bound").right
val logsParam <- properties.get("logs").toRight('debug -> "'logs' not defined in the configuration").right
val array <- checkType(logsParam).toRight('warning -> "unknown type of 'logs' confguration parameter").right}
yield array
lookup.fold(failure => { failure match {
case ('warning, msg) => log(LogService.WARNING, msg)
case ('debug, msg) => log(LogService.DEBUG, msg)
case _ =>
}; new Array[String](0) }, success => success)
}
(请注意,这是一个真实项目的片段,所以它不会自行编译)
我很高兴知道您Either
在代码中的使用方式和/或重构上述代码的更好想法。