2017-10-16 88 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) 

我希望這能解決你的問題