42

I'm using Typesafe config & have a config file in my resources directory which looks like this:

something {
  another {
    someconfig=abc
    anotherconfig=123
  }
}

How would I change the value of anotherconfig using scala?

ToYonos
  • 16,469
  • 2
  • 54
  • 70
goo
  • 2,230
  • 4
  • 32
  • 53

2 Answers2

92

If you want to change the loaded config (i.e. create a new config based on the old one), you can use withValue:

val newConfig = oldConfig.withValue("something.another.anotherconfig",
  ConfigValueFactory.fromAnyRef(456))
Synesso
  • 37,610
  • 35
  • 136
  • 207
Christian
  • 4,543
  • 1
  • 22
  • 31
12

You can't overwrite a value in the original Config object since it's immutable. What you can do is create a new Config object with your values, using the original as a fallback. So:

val myConfig = ConfigFactory.parseString("something.another.anotherconfig=456")
val newConfig = myConfig.withFallback(oldConfig)

and then use newConfig everywhere instead of your original Config. A more maintainable option would be to have a 2nd config file with your changes and use:

val myConfig = ConfigFactory.load("local")
val oldConfig = ConfigFactory.load
val realConfig = myConfig.withFallback(oldConfig)

You could then use a System Property to set where to load myConfig from.

Mario Camou
  • 2,303
  • 16
  • 28