Search code examples
typesafetypesafe-confighocon

Do not override variable in hocon files


I have a variable 'prefix' defined with default value 'base_' in base.conf file as below

prefix: base_
propObject: {
   property: {prefix}property
}

And I have two other files child1.conf and child2.conf that inherit base.conf and use propObject defined in it

include "base.conf"
prefix: child1_
child1Object: {
   property: ${propObject}
}
include "base.conf"
prefix: child2_
child2Object: {
   property: ${propObject}
}

And finally, all these files are included in final.conf file that looks like below:

include "base.conf"
include "child1.conf"
include "child2.conf"

I want child1Object's property to be called child1_property and child2Object's property to be called child2_property but only the most recent value is getting assigned to the prefix (it's always child2_property). Is there a way to resolve prefix per file?


Solution

  • Semantically, HOCON is basically a sequence of setting property values to possibly include lazily-evaluated substitutions and then evaluating the substitutions. There is thus, when evaluating substitutions like ${propObject} only ever one value of prefix: the last one assigned.

    This should work, however:

    include "base.conf"
    
    child1Object {
      property: ${propObject}
      property.property: "child1_property"
    }
    
    child2Object {
      property: ${propObject}
      property.property: "child2_property"
    }
    

    or (less legibly IMO):

    include "base"
    
    child1Object {
      property: ${propObject} { property = "child1_property" }
    }
    
    child2Object {
      property: ${propObject { property = "child2_property" }
    }
    

    Obviously if propObject has a lot of substitutions involving prefix, this will get out of hand... at that point, some form of templating is probably what you need.