相关疑难解决方法(0)

使用Either处理Scala代码中的失败

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)

functional-programming scala either

50
推荐指数
3
解决办法
2万
查看次数

在scala中使用异常是不好的做法吗?

我已经看过很多次使用Option(对于简单值)或者[List [Error],T]来处理错误的scala代码.

这给了这样的代码

def createApplicationToken(accessToken: AccessToken): Either[List[Error], ApplicationToken] = {

// go to social info provider and fetch information
retrieveProviderInfo(accessToken).fold(
  errors  => Left(errors),
  info    => {
    // try to find user using the info from the provider
    // if it's not there, create user
    User.findOrCreateFromProviderInfo(info).fold(
      errors  => Left(errors),
      user    => {
        // try to create a fresh token and save it to the user
        user.refreshApplicationToken.fold(
          errors  => Left(errors),
          user    => Right(user.token)
        )
      }
    )
  }
)
Run Code Online (Sandbox Code Playgroud)

这会产生一个不太好的代码嵌套,迫使你处理每一步的失败,并迫使你让所有的函数返回一个Either [...]

所以我想知道是否

  • 在scala(或一般的函数式编程)中不鼓励使用异常 …

error-handling functional-programming scala exception

23
推荐指数
2
解决办法
4094
查看次数