【发布时间】:2010-11-14 16:00:06
【问题描述】:
Option monad 是在 Scala 中处理“有或无”事物的一种极好的表达方式。但是,如果在“什么都没有”发生时需要记录一条消息怎么办?根据 Scala API 文档,
Either 类型通常用作 替代 scala.Option where Left 代表失败(按照惯例)和 权利类似于 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)
}
(请注意这是一个真实项目的sn-p,所以它不会自行编译)
我很高兴知道您如何在代码中使用 Either 和/或重构上述代码的更好想法。
【问题讨论】:
-
我在奥德斯基的书中也找不到任何提及。
-
是的,我有“Scala 编程”,但在其中找不到任何提及 Either。我所知道的最好的类比是 Liftweb 中的 Box,它也用于承载故障——它类似于 Option,但具有额外的功能。
-
有什么比
Option[Either[Foo, Bar]]更好的替代品吗?
标签: scala functional-programming either