scalajvmconfigtypesafehocon

HOCON does not override value in case substitution is used


I am using a HOCON configuration file which also has substitution variables. But in the case of substitution variables, the key is not overridden by another value into the same file. For example, consider the following HOCON config:

    {
        "x":5
        "x":6
        "y":{"a":1}
        "y":{"a":11}
        "z":${y.a}
        "z":${y.a}
    }

Now when I load this from ConfigFactor.parseURL, the resulted config is:

{"x":6,"y":{"a":11},"z":${y.a},"z":${y.a}}

Here y has to be resolved, but this does not happen with z.

Questions:

  1. What is the reason for this output?
  2. How could be enabled to resolve "z" as well?

Solution

  • You're just parsing the config file without resolving it. You have to call resolve() method.

    Check following example

    val options: ConfigRenderOptions = ConfigRenderOptions
      .defaults()
      .setComments(false)
      .setOriginComments(false)
      .setFormatted(false)
      .setJson(true)
    
    val parsed = ConfigFactory.parseString("""
    |{
    | "x":5
    | "x":6
    | "y":{"a":1}
    | "y":{"a":11}
    | "z":${y.a}
    | "z":${y.a}
    |}
    |""".stripMargin)
    
    println(parsed.root().render(options))
    println(parsed.resolve().root().render(options))
    
    

    Prints

    {"x":6,"y":{"a":11},"z":${y.a},"z":${y.a}}
    {"x":6,"y":{"a":11},"z":11}
    
    

    Please note that parse/resolve methods are used for advanced/customised configuration loading.

    If you are just loading application.conf and reference.conf files, I suggest to stick to load* methods only. Or use ConfigFactory.load(ConfigFactory.parse...) way of resolving the parsed config.