【问题标题】:Parsing an empty property into an empty Map with PureConfig使用 PureConfig 将空属性解析为空 Map
【发布时间】:2021-04-17 13:06:53
【问题描述】:

我有一个类似下面的案例类:

case class MyConfig(arg1:String, extraArgs:Map[String,String])

我希望可以从 HOCON 配置中解析以下内容

{
    arg1 = 'hello world'
}

但是这失败了,因为extraArgs 没有定义。我可以在我的案例类中将extraArgs 设为可选,但这将是多余的。有没有办法指示 PureConfig 将缺少的字段解析为空集合?

【问题讨论】:

  • 如果你给它一个默认参数,它会起作用吗?
  • 是的,虽然我不是默认参数的忠实粉丝
  • 对不起,这是我能做的最好的了 :)

标签: scala hocon pureconfig


【解决方案1】:

正如@LuisMiguelMejíaSuárez 在评论中建议的那样,您应该添加一个默认参数:

import pureconfig._
import pureconfig.generic.auto._
import com.typesafe.config.ConfigFactory

case class MyConfig(url: String, m: Map[String, String] = Map.empty)

val config1 = ConfigFactory.parseString("""{ "url": "https" }""")
val config2 = ConfigSource.fromConfig(config1).load[MyConfig]
println(config2)

代码在Scastie 运行。

【讨论】:

    猜你喜欢
    • 2015-09-04
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多