Optionmonad是一种很好的表达方式来处理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 …Run Code Online (Sandbox Code Playgroud)