Search code examples
scalatypesafe-confighocon

Merge array values in configuration using withFallBack in typesafe config


I have some data available as type safe configuration files in HOCON format.

There is a base-file like this :

"data":{
  "k1":{
    "values": ["v1", "v2"]
  },
  "k2":{
    "values": ["x1"]
  },
  "k3":{
    "values": ["z1"]
  }
}

There could be a file which can be used to make some changes, for example during test, like this:

"data":{
  "k1":{
    "values": ["v9"]
  }
}

I am trying to merge these two files using

fileConfig.withFallback(baseFileConfig)

The end result is:

"data":{
  "k1":{
    "values": ["v9"]  // desired ["v1","v2","v9"]
  },
  "k2":{
    "values": ["x1"]
  },
  "k3":{
    "values": ["z1"]
  }
}

i.e. the array values for "k1" from the fallBack configuration are ignored. Is there a way I can get the concatenated array from two files after the merge?


Solution

  • for do that you need add ref for values concatenation (values: ${data.k1.values} ["v9"]):

    lazy val defaultConfig     = ConfigFactory.parseResources("a.conf")
    lazy val additionalConfig = ConfigFactory.parseResources("b.conf" )
    println(additionalConfig.withFallback(defaultConfig).resolve()) 
    // Config(SimpleConfigObject({"data":{"k1":{"values":["v1","v2","v9"]},"k2":{"values":["x1"]},"k3":{"values":["z1"]}}}))
    

    configs:

    defaultConfig

    data: {
      k1: {
        values: ["v1", "v2"]
      },
      k2: {
        "values": [
          "x1"
        ]
      },
      k3: {
        "values": [
          "z1"
        ]
      }
    }
    

    additionalConfig:

    data: {
      k1: {
        values: ${data.k1.values} ["v9"]
      }
    }