2017-10-16 86 views
0

是否可以使用以下级别的抽象级别在Scala中使用Typesafe Config和pureconfig创建以下方法? 我知道定义的案例分类配置读者必须被指定为follows,因为以下limitations ...但任何类型的案例类...如果他们都实施了他们的配置读者?找不到参数阅读器的隐含值:pureconfig.ConfigReader [T]

/** 
     * @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") 
     } 
    } 
    } 

回答

1

我假设你的建造时间错误,如 “错误:(17,18)无法找到参数读者隐含值:pureconfig.ConfigReader [T] loadConfig [T] ... ”

错误在于pureconfig的loadConfig方法没有找到它的reader参数的隐式值。一个解决方案是明确给出隐式读取器参数。您的方法getConfigType可以将隐式读取器作为参数,以便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) 

我希望这能解决你的问题