找不到参数 reader 的隐式值:pureconfig.ConfigReader[T]

could not find implicit value for parameter reader: pureconfig.ConfigReader[T]

是否可以在 scala 中使用 Typesafe Config 和 pureconfig 创建具有以下抽象级别的以下方法? 我知道对于已定义的 Case 类,Config Reader 必须指定为 follows , because of the following limitations ...但是任何类型的 Case class ...如果它们都有他们的配置 Reader 已实施 ?

    /**
      * @param path the.path.to.the.branch
      * @param config the com.typesafe.config obj
      * @tparam T - the type of the case class obj
      * @return the filled-in obj of type T
      *
      */
    def getConfigType[T](path: String, config :Config) :Option[T] = {

      val renderOpts = ConfigRenderOptions.defaults
        .setOriginComments(false).setComments(false).setJson(true)
      val levelConfig :Config = config.getConfig(path)
      val strConfig: String = config.getConfig(path).root().render(renderOpts)

      loadConfig[T](ConfigFactory.parseString(strConfig)) match {
        case Right(objFilledCaseClass) => Some(objFilledCaseClass)
        case Left(errors) => throw new RuntimeException(s"Invalid configuration: $errors")
      }
    }
  }

我假设您遇到构建时错误,例如 “错误:(17, 18) 找不到参数 reader 的隐式值:pureconfig.ConfigReader[T] 加载配置 [T]... “

错误是 pureconfig 的 loadConfig 方法没有找到它的 reader 参数的隐式值。一种解决方案是显式提供隐式 reader 参数。您的方法 getConfigType 可以采用隐式 reader 作为参数,因此 getConfigType 接口的行为就像 loadConfig 的行为一样。

所以解决方案是将接口定义为:

import pureconfig.{ConfigReader, loadConfig}
// Is there a reason why return type is Option? Method either returns Some or throws exception
def getConfigType[ConfigType](path: String, config :Config)(implicit reader: ConfigReader[ConfigType]):ConfigType = 
{
...
loadConfig(ConfigFactory.parseString(strConfig))(reader) match {
...
}
...
}

然后你称它为:

case class YourCustomType()
import eu.timepit.refined.pureconfig._
getConfigType[YourCustomType](path, config)

希望这能解决您的问题

添加 pureconfig.generic.auto.exportReader 的导入。这提供了所需的隐式配置 reader.

致谢与参考:https://blog.knoldus.com/4-easy-steps-to-load-configuration-with-pure-config/