在类型安全的配置 getter 上提供默认值

vat*_*ada 6 refactoring scala typesafe

所以我的代码中多次出现类似的片段:

val optionValue = try {
      Some(config.getString(key))
    } catch {
      case _: Missing => None
    }
Run Code Online (Sandbox Code Playgroud)

我想以某种方式从我的代码中消除这些重复项。我知道 typesafe 提供了一种提供后备配置文件以提供默认配置值的方法。但是,就我而言,某些属性没有任何默认值。它们是可选属性。

重构此代码的最佳方法是什么。

Tho*_*aux 7

根据https://github.com/lightbend/config#how-to-handle-defaults,这不是图书馆的工作方式。

您应该使用withFallbackmethod 来提供干净的配置。


Jac*_*cko 5

由于您使用的是 Scala,并且假设您可以使用隐式,我会采用推荐的使用丰富类的方法,该方法允许您保留Option语法。

示例配置。

existent.sample.string="I exist!"
existent.sample.boolean=true
Run Code Online (Sandbox Code Playgroud)

示例丰富类。

package config

import com.typesafe.config.{Config, ConfigException}

object MyConfig {

  implicit class RichConfig(val config: Config) extends AnyVal {
    def optionalString(path: String): Option[String] = if (config.hasPath(path)) {
      Some(config.getString(path))
    } else {
      None
    }

    def optionalBoolean(path: String): Option[Boolean] = if (config.hasPath(path)) {
      Some(config.getBoolean(path))
    } else {
      None
    }

    // An example of using the exception approach - but less efficient than using hasPath
    def optionalString2(key: String): Option[String] = try {
      Some(config.getString(key))
    } catch {
      case _: ConfigException => None
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,最好使用hasPath(而不是使用 a Try)来检查您的场景中是否存在一个键,而不是让 JVM 创建一个对可选配置不感兴趣的异常。允许不存在。

演示。

import com.typesafe.config._

object ConfigTest extends App {

  import MyConfig._

  val conf = ConfigFactory.load

  val optionalString = conf.optionalString("existent.sample.string")
  val optionalStringNone = conf.optionalString("non-existent.sample.string")

  println(s"String config value: $optionalString")
  println(s"Optional (non-existent) String config value: $optionalStringNone")

  val optionalBoolean = conf.optionalBoolean("existent.sample.boolean")
  val optionalBooleanNone = conf.optionalBoolean("non-existent.sample.boolean")

  println(s"Boolean config value: $optionalBoolean")
  println(s"Optional (non-existent) String config value: $optionalBooleanNone")

}
Run Code Online (Sandbox Code Playgroud)

印刷。

// String config value: Some(I exist!)
// Optional (non-existent) String config value: None
// Boolean config value: Some(true)
// Optional (non-existent) String config value: None
Run Code Online (Sandbox Code Playgroud)

文档