Yor*_*iev 1 types scala typesafe pureconfig
我知道这违反了Scala pureconfig的本质......但是......使用scala pureconfig配置读取这个case类甚至是可行的,所以它不是为构造函数提供强类型值(作为String)参数"variable"有任何类型或至少String,Integer,Double,Array [Strings],Array [Integer],Array [Double].
case class Filter(
field: String,
operator: String,
variable: String // should support Int , Double , List[String], List[Int]
)
Run Code Online (Sandbox Code Playgroud)
据我所知,CoProductHint和Custom Reader方法都不会起作用......
默认情况下,pureconfig不提供读取方式Any.如果对于您想要阅读的特定类,Any则可以Any在该类的上下文中定义编解码器:
case class Filter(field: String, operator: String, variable: Any)
implicit val readFilter = {
implicit val readAny = new ConfigReader[Any] {
def from(config: ConfigValue): Either[ConfigReaderFailures, Any] = {
Right(config.unwrapped())
}
}
ConfigReader[Filter]
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以阅读了 Filter
val config = ConfigFactory.parseString(
"""
{
field: "foo"
operator: "bar"
variable: []
}
""")
println(pureconfig.loadConfig[Filter](config))
// will print Right(Filter(foo,bar,[]))
Run Code Online (Sandbox Code Playgroud)
unwrapped将a转换ConfigValue为Any递归.
所以答案是肯定的,如果有可能告诉pureconfig如何阅读Any.
pureconfig Any默认不提供编解码器的原因是因为它Any是Scala中所有类的祖先,并且不可能为任何事物(例如数据库连接)创建编解码器.当您知道您期望一组受限制的类型(例如您列出的类型)时,您可以将所有内容包装在副产品中:
sealed abstract class MySupportedType
final case class MyInt(value: Int) extends MySupportedType
final case class MyDouble(value: Double) extends MySupportedType
final case class MyListOfString(value: List[String]) extends MySupportedType
final case class MyListOfInt(value: List[Int]) extends MySupportedType
final case class Filter2(field: String, operator: String, variable: MySupportedType)
Run Code Online (Sandbox Code Playgroud)
然后使用默认方式提取coproduct值或自定义编解码器 MySupportedType
val config = ConfigFactory.parseString(
"""
{
field: "foo"
operator: "bar"
variable: {
type: mylistofint
value: []
}
}
""")
println(pureconfig.loadConfig[Filter2](config))
// will print Right(Filter2(foo,bar,MyListOfInt(List())))
Run Code Online (Sandbox Code Playgroud)
使用副产品而不是Any限制可能具有的值,variable如果您正在做的事情出错,编译器会帮助您.