lev
lev

Reputation: 4127

Re-resolve a scala config object

I would like to re-resolve a config object. for example if I define this config:

val conf = ConfigFactory.parseString(
  """
    | foo = a
    | bar = ${foo}1
    | baz = ${foo}2
  """.stripMargin).resolve()

I will get those values:

conf.getString("bar") //res0: String = a1
conf.getString("baz") //res1: String = a2

given the object conf, what I want is to be able to change the value of foo, and get updated values for bar and baz. Something like :

val conf2 = conf
             .withValue("foo", ConfigValueFactory.fromAnyRef("b"))
             .resolve()

and get:

conf2.getString("bar") //res0: String = b1
conf2.getString("baz") //res1: String = b2

but running this code will result in:

conf2.getString("foo") //res0: String = b
conf2.getString("bar") //res1: String = a1
conf2.getString("baz") //res2: String = a2

is this even possible?

Upvotes: 3

Views: 678

Answers (1)

Ben Reich
Ben Reich

Reputation: 16324

It's not possible once resolve is called. In the documentation for resolve, it says:

Returns a replacement config with all substitutions resolved... Resolving an already-resolved config is a harmless no-op.

In other words, once you call resolve, all the substitions occur, and there is no reference to the original HOCON substitution syntax.

Of course, you can keep the unresolved Config object as a variable, and then use withValue:

val rawConf = ConfigFactory.parseString(
  """
    | foo = a
    | bar = ${foo}1
    | baz = ${foo}2
  """.stripMargin)
val conf2 = rawConf.withValue("foo", ConfigValueFactory.fromAnyRef("b")).resolve
val conf = rawConf.resolve

conf.getString("bar") //a1
conf2.getString("bar") //b1, as desired

Upvotes: 4

Related Questions